大网数据广告活动
网站运营与故障问答

Why does RewriteRule for "^//(.*)" (begins with double slash) not redirect to a single slash?

· 52CE 我爱测

Have this rewrite rule in vHost context. But it does not rewrite requests that begin with //.* (double slash). Just serves them up from /.* (single slash) instead of responding with a redirect to /.* RewriteRule "^//(.*)" "/$1" […

问题原文

原帖链接 · NOYB · CC BY-SA 4.0

Have this rewrite rule in vHost context. But it does not rewrite requests that begin with //.* (double slash). Just serves them up from /.* (single slash) instead of responding with a redirect to /.*

RewriteRule "^//(.*)" "/$1" [R=301,L]

Why doesn't this work?

已采纳解答

原帖链接 · MrWhite · CC BY-SA 4.0

RewriteRule "^//(.*)" "/$1" [R=301,L]

This will never match because the URL-path that the RewriteRule pattern matches against has already had all instances of multiple slashes reduced to a single slash.

To redirect such requests you can make use of this "feature" and simply redirect "to itself" and check against THE_REQUEST server variable instead in order to determine whether multiple slashes were present on the initial request. THE_REQUEST is the first line of the request header and contains the raw unprocessed request URL (excluding protocol and hostname, but including the query string) as sent from the client.

For example, to redirect all instances of multiple slashes to a single slash throughout the URL-path, not just at the start then you can do something like this:

RewriteCond %{THE_REQUEST} \s[^?]*//
RewriteRule (.*) $1 [R=301,L]

The regex \s[^?]*// ensures we don't match multiple slashes in the query string part of the URL (which would otherwise result in a redirect loop).


Would RewriteCond %{THE_REQUEST} ^// allow us to apply the rewrite rule to only those that begin with double slashes, ignoring all other instances of double slashes?

Not quite, THE_REQUEST server variable actually contains the entire first line of the HTTP request header. In other words, a string of the form:

GET /foo/bar.html HTTP/1.1

Or GET //foo/bar.html HTTP/1.1 if there is a double slash at the start of the URL-path, so you would need something like this instead:

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

...in order to catch all request methods. And specifically just a double slash, not triple slashes, etc. at the start of the URL-path only.

\s//[^/] - That's a space (after the request method) followed by 2 slashes and something other than a slash (ie. either a space for the document root, or some other URL-path).

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Webmasters Stack Exchange
适用范围
以原帖系统、软件版本与发布日期为准(2020-08-17)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。