如何在 nginx 中使用尾部斜杠配置重定向到 url?

How to configure redirects to url with trailing slash in nginx?

我想将不带斜线的 URL 重定向到带尾部斜线的路径。 所以 /some-url/some-url/

以及其余的网址,例如

应该保持不变。

我找到了这篇文章 https://www.ateamsystems.com/tech-blog/nginx-add-trailing-slash-with-301-redirect-without-if-statements/,其中作者建议使用以下规则:

location ~ ^([^.\?]*[^/])$ {
   try_files $uri @addslash;
}

location @addslash {
    return 301 $uri/;
}

不幸的是,这实际上不起作用。因为 url /some-url?q=v 被重定向到 /some-url/

您能否建议如何更改正则表达式以使其正常工作?

查询字符串从 ? 开始,不是匹配 locationrewrite 指令时使用的规范化 URI 的一部分。整个 URI 可作为 $request_uri 变量使用。您可以在 if 块中使用您的正则表达式:

if ($request_uri ~ ^([^.?]*[^/])$ ) { return 301 /; }

参见 this document for more, and this caution 关于 if 的使用。

这应该可以解决问题:

location / {
    if ($request_uri ~ ^([^.\?]*[^/])$) {
        return 301 /;
    }

    try_files $uri $uri/ /index.php$is_args$args;
}

我想出了如何在没有 if 语句的情况下做到这一点!这解决了您提到的所有问题(案例 #2 除外,在案例 #3 中它重定向但保留查询字符串)。

# 301 try_file for trailing slash
location ~ ^([^.\?]*[^/])$ {
  try_files $uri @addslash;
}

# 301 redirect for trailing slash
location @addslash {
  return 301 $uri/$is_args$args;
}

# Root directory location handler
location / {
    try_files $uri/index.html $uri $uri/ /index.php?$query_string;
}