nginx与apache的rewrite规则的区别
1. nginx rewrite规则相关指令
nginx rewrite规则相关指令有if、rewrite、set、return、break等,其中rewrite是最关键的指令。一个简单的nginx rewrite规则语法如下:
rewrite ^/b/(.*)\.html /play.php?video=$1 break;
如果加上if语句,示例如下:
if (!-f $request_filename)
{ rewrite ^/img/(.*)$ /site/$host/images/$1 last; }
2. nginx与apache的rewrite规则实例对比
简单的nginx和apache 重写规则区别不大,基本上能够完全兼容。
apache rewrite 规则:
rewriterule ^/(mianshi|xianjing)/$ /zl/index.php?name=$1 [l]
rewriterule ^/ceshi/$ /zl/ceshi.php [l]
rewriterule ^/(mianshi)_([a-za-z] )/$ /zl/index.php?name=$1_$2 [l] rewriterule ^/pingce([0-9]*)/$ /zl/pingce.php?id=$1 [l]
nginx rewrite 规则:
rewrite ^/(mianshi|xianjing)/$ /zl/index.php?name=$1 last;
rewrite ^/ceshi/$ /zl/ceshi.php last;
rewrite ^/(mianshi)_([a-za-z] )/$ /zl/index.php?name=$1_$2 last;
rewrite ^/pingce([0-9]*)/$ /zl/pingce.php?id=$1 last;
不难发现apache的rewrite规则改为nginx的rewrite规则挺简单的,如果改完规则,使用"nginx -t"命令检查发现nginx.conf配置文件有语法错误,那么可以尝试给条件加上引号。例如一下的nginx rewrite规则会报语法错误:
rewrite ^/([0-9]{5}).html$ /x.jsp?id=$1 last;加上引号就正确了:
rewrite “^/([0-9]{5}).html$” /x.jsp?id=$1 last;
apache与nginx的rewrite规则在url跳转时有细微的区别:
apache rewrite 规则:
rewriterule ^/html/tagindex/([a-za-z] )/.*$ /$1/ [r=301,l]
nginx rewrite 规则:
rewrite ^/html/tagindex/([a-za-z] )/.*$ http://$host/$1/ permanent;
以上示例中,我们注意到,nginx rewrite 规则的置换串中增加了“http://$host”,这是在nginx中要求的。
另外,apache与nginx的rewrite规则在变量名称方面也有区别,例如:
apache rewrite 规则:
rewriterule ^/user/login/$ /user/login.php?login=1&forward=http://%{http_host} [l]
nginx rewrite 规则:
rewrite ^/user/login/$ /user/login.php?login=1&forward=http://$host last;
apache与nginx rewrite 规则的一些功能相同或类似的指令、标记对应关系:
apache的rewritecond指令对应nginx的if指令;
apache的rewriterule指令对应nginx的rewrite指令;
apache的[r]标记对应nginx的redirect标记;
apache的[p]标记对应nginx的last标记;
apache的[r,l]标记对应nginx的redirect标记;
apache的[p,l]标记对应nginx的last标记;
apache的[pt,l]标记对应nginx的last标记;
允许指定的域名访问本站,其他域名一律跳转到http://www.aaa.com:
apache rewrite 规则:
rewritecond %{http_host} ^(.*?)\.domain\.com$
rewritecond %{http_host} !^qita\.domain\.com$ rewritecond %{document_root}/market/%1/index.htm -f
rewriterule ^/wu/$ /market/%1/index.htm [l]
nginx的if指令不支持嵌套,也不支持and、or等多条件匹配,相比于apache的rewritecond,显得麻烦一些,但是,我们可以通过下一页的nginx配置写法来实现这个示例:
nginx rewrite 规则:
if ($host ~* ^(.*?)\.domain\.com$)
{
set $var_wupin_city $1;
set $var_wupin ‘1′;
}
if ($host ~* ^qita\.domain\.com$)
{
set $var_wupin ‘0′;
}
if (!-f $document_root/market/$var_wupin_city/index.htm)
{
set $var_wupin ‘0′;
}
if($var_wupin ~ ‘1′)
{
rewrite ^/wu/$ /market/$var_wupin_city/index.htm last;
}
备注学习:
rewrite ^/serach/(.*).html http://www.xxx.com/search.action?keywords=$1 last;
访问http://www.xxx.com/search/mp3.html,浏览器url重定向为http://www.xxx.com/search.action?keywords=mp3
posted on 2011-12-14 17:35
-274°c 阅读(5545)
评论(1) 编辑 收藏 所属分类:
nginx