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

How to remove trailing slash when redirecting to a new page in Nginx

我正在尝试修改 URLs 并将流量重定向到新的 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/ permanent;}
    location ~* /(.*)/$ { return 301 https://example.com/;}
  1. 通过在我现有的位置块中添加重写并以某种方式修改 $request_uri,例如:
location / { 
 rewrite ^/(.*)/$ / break;
 return 301 https://example.com$request_uri; 
}

显然,上面的代码片段不起作用,非常感谢您的帮助。

您需要使用 rewrite 删除结尾的 /。但是在你的例子中,第一次捕获太贪心了。使用 *? 作为惰性量词。

例如:

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