如何删除 nginx 服务的 URL 中的双斜杠?

cod*_*boy 12 rewrite nginx

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

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

小智 7

我想建议这种方法:

# 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;
}
Run Code Online (Sandbox Code Playgroud)

它使用了 nginx 的默认行为——合并斜杠,所以我们不需要替换斜杠,我们只需重定向

在这里找到


小智 5

我发现 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"
Run Code Online (Sandbox Code Playgroud)

我发现这对我有用:

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

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


小智 2

尝试这个:

merge_slashes off;
rewrite (.*)//+(.*) $1/$2 permanent;
Run Code Online (Sandbox Code Playgroud)

斜杠 > 3 或多组斜杠可能有多个重定向。

  • @Jonathan - 我也刚刚遇到过这个。我的理解是,“merge_slashes on”并不符合您的想法。它基本上告诉 nginx 将 // 和 / 和 /// 作为单个斜杠(不要自行合并和重定向) (2认同)