需求:将http://www.zhoufengjie.cn/?want=rewrite&direct=new重定向到http://zhoufengjie.cn/?want=rewrite&direct=old
实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<span style="color: #ff6600;">server {</span> <span style="color: #ff6600;"> listen 80;</span> <span style="color: #ff6600;"> server_name www.zhoufengjie.cn;</span> <span style="color: #ff6600;"> ................</span> <span style="color: #ff6600;"> location / {</span> <span style="color: #ff6600;"> if ($request_uri ~ ^/\?want=rewrite\&direct=new$ ){</span> <span style="color: #ff6600;"> #rewrite "^/.*" http://zhoufengjie.cn/?want=rewrite&direct=old? break;</span> <span style="color: #ff6600;"> rewrite "^/.*" http://zhoufengjie.cn/?want=rewrite&direct=old? redirect;</span> <span style="color: #ff6600;"> }</span> <span style="color: #ff6600;"> ................</span> <span style="color: #ff6600;"> }</span> <span style="color: #ff6600;">}</span> |
这里必须注意一个事项,就是重定向后的内容最后增加一个?号,之前我测试一直会在后面增加原有的参数,变成:http://zhoufengjie.cn/?want=rewrite&direct=old&want=rewrite&direct=new,只要不加?号,nginx就会把内容放上;我因此查看了一下nginx的代码(nginx-1.7.7/src/http/modules/ngx_http_rewrite_module.c),在346行到353行,如下内容:
1 2 3 4 5 6 7 8 9 10 |
<span style="color: #ff6600;">if (value[2].data[value[2].len - 1] == '?') {</span> <span style="color: #ff6600;">/* the last "?" drops the original arguments */</span> <span style="color: #ff6600;"> value[2].len--;</span> <span style="color: #ff6600;">} else {</span> <span style="color: #ff6600;"> regex->add_args = 1;</span> <span style="color: #ff6600;"> }</span> |