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

问题描述

我正在尝试修改 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; 
}

显然,上述代码段不起作用,我将感谢您的帮助。

解决方法

您需要使用 rewrite 删除尾随的 /。但是在您的示例中,第一次捕获过于贪婪。使用 *? 作为惰性量词。

例如:

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