如何在Nginx中重定向到新页面时删除尾随斜杠

thigvfpy  于 2023-10-17  发布在  Nginx
关注(0)|答案(3)|浏览(202)

我正在尝试修改URL并将流量重定向到一个没有尾随斜杠的新URL。下面是我当前的服务器块:

  1. server {
  2. listen 443 ssl;
  3. server_name www.example.com;
  4. ssl_certificate /path/to/certificate.crt;
  5. ssl_certificate_key /path/to/private/key.pem;
  6. ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
  7. # redirects manually entered here:
  8. location /long-url-1/ { return 301 https://example.com/short-url-1; }
  9. location /long-url-2/ { return 301 https://example.com/short-url-2; }
  10. # all other traffic should be redirected by the rule below:
  11. location / { return 301 https://example.com$request_uri; }
  12. }

我想修改以下位置块:

  1. # all other traffic should be redirected by the rule below:
  2. location / { return 301 https://example.com$request_uri; }

如果用户输入:

  1. 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)

或者如果用户输入:

  1. 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,例如:

  1. location / { rewrite ^/(.*)/?$ https://example.com/$1 permanent;}
  2. location ~* /(.*)/$ { return 301 https://example.com/$1;}

1.通过在我现有的位置块中添加重写并以某种方式修改$request_uri,例如:

  1. location / {
  2. rewrite ^/(.*)/$ /$1 break;
  3. return 301 https://example.com$request_uri;
  4. }

显然,上述片段不工作,我将感谢您的帮助。

vmjh9lq9

vmjh9lq91#

您需要使用rewrite删除尾随的/。但在你的例子中,第一次捕获太贪婪了。使用*?作为惰性量词。
举例来说:

  1. location / {
  2. rewrite ^(/.*?)/?$ https://example.com$1 permanent;
  3. }
fjaof16o

fjaof16o2#

https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#taxing-rewrites

  1. location ~ (?<no_slash>.*)/$ {
  2. return 301 $scheme://$host$no_slash;
  3. }
7y4bm7vi

7y4bm7vi3#

该解决方案也经过测试,运行良好。
它应该有更好的性能,因为根据上面的最佳实践没有重写。

  1. location ~ (.*?\/)(\/+)$ {
  2. return 301 $scheme://$host$request_uri;
  3. }

相关问题