如何删除 nginx 提供的 URL 中的双斜杠?

如何删除 nginx 提供的 URL 中的双斜杠?

我需要在 Ubuntu 12.04 上的 Nginx 配置中复制以下 Apache 重写规则。nginx 相当于什么:

RewriteCond %{REQUEST_URI} ^(.*)//(.*)$
RewriteRule . %1/%2 [R=301,L]

答案1

我想建议采用这种方法:

# remove multiple sequences of forward slashes
# rewrite URI has duplicate slashes already removed by Nginx (merge_slashes on), just need to rewrite back to current location
# note: the use of "^[^?]*?" avoids matches in querystring portion which would cause an infinite redirect loop
if ($request_uri ~ "^[^?]*?//") {
rewrite "^" $scheme://$host$uri permanent;
}

它使用 nginx 的默认行为 - 合并斜杠,因此我们不需要替换斜杠,只需重定向

找到这里

答案2

我发现 kwo 的响应不起作用。查看我的调试日志,发生了以下情况:

2014/08/18 15:51:04 [debug] 16361#0: *1 http script regex: "(.*)//+(.*)"
2014/08/18 15:51:04 [notice] 16361#0: *1 "(.*)//+(.*)" does not match "/contact-us/", client: 59.167.230.186, server: *.domain.edu, request: "GET //////contact-us//// HTTP/1.1", host: 
"test.domain.edu"

我发现这对我有用:

if ($request_uri ~* "\/\/") {
  rewrite ^/(.*)      $scheme://$host/$1    permanent;
}

参考:http://rosslawley.co.uk/archive/old/2010/01/10/nginx-how-to-url-cleaning-removing/

答案3

尝试这个:

merge_slashes off;
rewrite (.*)//+(.*) $1/$2 permanent;

对于斜线 > 3 或多组斜线,可能会有多次重定向。

答案4

我喜欢这个解决方案:

if ($request_uri ~ "//") {
    return 301 $uri;
}

https://stackoverflow.com/a/27071557/548473

相关内容