问题原文
原帖链接 · 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).
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
