url重写 - nginx重写:如果$uri 不是文件不是目录 跳转到$uri/

浏览:36日期:2022-07-04

问题描述

配置

nginx 1.6.2

要求

访问

$uri

如果

1)如果 存在文件 /Vhost/$http_host/$uri ,访问的是该文件2)否则 如果 $uri 不是以 “/” 结尾 301 跳转到 $uri/3)否则 如果 $uri 以 “/” 结尾 且 存在 /Cache/$http_host/$uri/index.html ,访问的是该文件4)否则 指向 /index.php (ThinkPHP框架)例子

访问 http://www.a.com/robots.txt -> /Vhost/www.a.com/robots.txt访问 http://a.com/robots.txt ->301 跳转 -> http://www.a.com/robots.txt访问 http://www.c.com/sitemap.html -> /Vhost/www.c.com/sitemap.html访问 http://www.d.com/game/ -> /Cache/www.d.com/game/index.html访问 http://www.d.com/news/1000011 -> 301 跳转到 -> http://www.d.com/news/1000011/访问 http://www.d.com/news/1000011/ -> /index.php (当该/Cache/www.d.com/news/1000011/index.html 不存在的时候)访问 http://www.d.com/news/1000011/ -> /Cache/www.d.com/news/100011/index.html (当该/Cache/www.d.com/news/1000011/index.html 存在的时候)配置

server { listen 80; server_name wap wap.loc m.wap.loc wap.loc m.xxx.com game1.wap.loc game2.wap.loc game3.wap.loc; location / {root d:/wap_dev;index index.html index.htm index.php; try_files $uri /Vhost/$http_host/$uri /Cache/$http_host/$uri/index.html /index.php?s=$uri&$args; location ~ .php$ { try_files $uri =404; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; includefastcgi_params; } } #error_page 404 /404.html; # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html {root html; } location ~ /.(ht|svn|git) {deny all; }}问题

已经实现了上面的1、3、4,还有2未实现。

上面第3)点打错字了,是如下的。已经修改了的,但是sg没有变化

3)否则 如果 $uri 以 “/” 结尾 且 存在 /Cache/$http_host/$uri/index.html ,访问的是该文件补充

1) 如何才可以 不是 以/结尾且不是以.xml结尾且不是以.html .htm结尾的才跳转

现在是不是以 /结尾的跳转,导致.xml 结尾 .html结尾的也都跳转自己写了一段,但是失败:

rewrite ([^/]|.xml|.html?)$ $uri/ permanent;

问题解答

回答1:

你需要使用一个 @ 开头的 named location 来解决这个问题。

# 如果找不到任何匹配的文件就会进入 @rewrite location 来决定如何 rewritetry_files $uri /Vhost/$http_host/$uri /Cache/$http_host/$uri/index.html @rewrite;location @rewrite { # 如果末尾不是 /,301 跳转 rewrite [^/]$ $uri/ permanent; # 默认交给 index.php 来处理 rewrite . /index.php?s=$uri&$args last;}回答2:

因爲你的規則自相矛盾。

2)否则 如果 $uri 不是以 “/” 结尾 301 跳转到 $uri/3)否则 如果 $uri 不是以 “/” 结尾 且 存在 /Cache/$http_host/$uri/index.html ,访问的是该文件

2 和 3 顯然不能同時滿足。

應改成

2) else if $uri 不是以 “/” 结尾 then 301 跳转到 $uri/3) else if $uri 以 “/” 结尾 and 存在 /Cache/$http_host/$uri/index.html then 访问该文件

實際上等價於

else if $uri 不是以 “/” 结尾 then 301 跳转到 $uri/else if 存在 /Cache/$http_host/$uri/index.html then 访问该文件

相关文章: