为什么重写(nginx)redirect301代码?

我有这样的configuration:

location ~ ^/myway(.*) { rewrite ^/myway(.*)$ /anotherway$1; rewrite_log on; error_log /var/log/nginx/errors notice; } location /anotherway { ... internal; } 

url: site.com/myway/可以正常工作(重写site.com/anotherway/ )。 但url: site.com/mywayredirectsite.com/anotherway/ 。 为什么? 应该给404错误?

您可以将(.*)更改为(.+)

.*匹配任何字符(除了换行符)量词:*零和无限次之间,尽可能多次,根据需要回馈[贪婪]

.+匹配任何字符(除了换行符)量词:+在一次和无限次之间,尽可能多的次数,根据需要回馈[贪婪]

这意味着:

  • /myway(.*) / myway(…)&myway /(…)
  • /myway(.+)匹配/ myway /(…)

如果指定的正则expression式与请求URI相匹配,则将按照replacestring中的指定更改URI。 重写指令按照其在configuration文件中的顺序依次执行。 可以使用标志终止对指令的进一步处理。 如果replacestring以“http://”或“https://”开头,则处理将停止,redirect将返回给客户端。

有关Nginx重写的更多信息: http : //nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite

顺便说一句,你可以在这里testing正则expression式: https : //regex101.com/

试试这个 – 我添加了几个斜杠。 不是100%确定它会工作,但值得一试。

 location ~ ^/myway/(.*) { rewrite ^/myway/(.*)$ /anotherway$1; rewrite_log on; error_log /var/log/nginx/errors notice; } 

它也可能与你的configuration文件中某处的try_files有关。