zyk198500 发表于 2018-11-8 12:00:09

nginx 匹配问号 rewrite

  今天同事问我 nignx跳转的问题匹配问号需要
  需求是http://aaa.bbb.com/forum.php?id=123 跳转到 http://aaa.bbb.com/forum.php
  在这里需要注意的是跳转前有问号,跳转后没有问号
  这种情况我是用if解决的。
  nginx有一个变量是$query_string 它的用途就是定义问号以后的变量

  在这个例子中它其实就是>  开始配置的时候是
if ($query_string ~* "id=123$") {  
   rewrite ^(.*) http://aaa.bbb.com/forum.php last;
  
}
  但是测试结果302死循环
  后来经过查看,nginx rewrite 会直接匹配问号之前的内容,问号后面的内容会直接添加rewrite
  这样就会造成,每次rewrite后的url 还会再添加id=123 这样,跳转前跟跳转后就没有区别了。
  效果就是
  http://aaa.bbb.com/forum.php?id=123 rewrite http://aaa.bbb.com/forum.php?id=123
  这个可以从http_header中的location中看出来。这样的跳转每次location都是
  http://aaa.bbb.com/forum.php?id=123。这样就造成死循环了。
  后来查看wiki nginx跳转去掉问号内容是这样操作的
  rewrite ^(.*) http://aaa.bbb.com/forum.php? last;
  就是在rewrite后的URL后面添加一个问号,这样,跳转前的问号内容就不再追加到挑战后的链接后面了。
  正确的配置就是:
if ($query_string ~* "id=123$") {  
   rewrite ^(.*) http://aaa.bbb.com/forum.php? last;
  
}


页: [1]
查看完整版本: nginx 匹配问号 rewrite