我正在尝试修改URL并将流量重定向到一个没有尾随斜杠的新URL。下面是我当前的服务器块:
server {
listen 443 ssl;
server_name www.example.com;
ssl_certificate /path/to/certificate.crt;
ssl_certificate_key /path/to/private/key.pem;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
# redirects manually entered here:
location /long-url-1/ { return 301 https://example.com/short-url-1; }
location /long-url-2/ { return 301 https://example.com/short-url-2; }
# all other traffic should be redirected by the rule below:
location / { return 301 https://example.com$request_uri; }
}
我想修改以下位置块:
# all other traffic should be redirected by the rule below:
location / { return 301 https://example.com$request_uri; }
如果用户输入:
https://www.example.com/unknown-url-1/ => (www + with slash) the rule should redirect to: https://example.com/unknown-url-1 (non-www + no trailing slash)
或者如果用户输入:
https://www.example.com/unknown-url-2 => (www + no slash) the rule should redirect to: https://example.com/unknown-url-2 (non-www + no trailing slash)
我认为有两种方法:
1.通过实现两个位置块,一个用于带有斜杠的URL请求,一个用于所有没有斜杠的URL,例如:
location / { rewrite ^/(.*)/?$ https://example.com/$1 permanent;}
location ~* /(.*)/$ { return 301 https://example.com/$1;}
1.通过在我现有的位置块中添加重写并以某种方式修改$request_uri
,例如:
location / {
rewrite ^/(.*)/$ /$1 break;
return 301 https://example.com$request_uri;
}
显然,上述片段不工作,我将感谢您的帮助。
3条答案
按热度按时间vmjh9lq91#
您需要使用
rewrite
删除尾随的/
。但在你的例子中,第一次捕获太贪婪了。使用*?
作为惰性量词。举例来说:
fjaof16o2#
https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#taxing-rewrites
7y4bm7vi3#
该解决方案也经过测试,运行良好。
它应该有更好的性能,因为根据上面的最佳实践没有重写。