mod_rewrite:删除尾部斜杠(只有一个!)
我使用 mod_rewrite/.htaccess 来获得漂亮的 URL。
我使用此条件/规则来消除尾随斜杠(或者更确切地说:通过 301 重定向重写到非尾随斜杠 URL;我这样做是为了避免重复内容,因为我喜欢没有尾随斜杠的 URL更好):
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{HTTP_HOST} !^\.localhost$ [NC] RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]
到目前为止工作良好。唯一的缺点:
它还将“多个尾随斜杠”URL 转发到“非尾随斜杠 URL”。
示例:http://example.tld/foo/bar//////
转发到 http://example.tld/foo/bar
而我只想将 http://example.tld/foo/bar/
转发到 http://example.tld/foo/bar
。
那么,如果实际上只有一个尾部斜杠,是否可以只消除尾部斜杠?
抱歉,如果这是一个有点烦人或奇怪的问题!
谢谢。
I use mod_rewrite/.htaccess for pretty URLs.
I'm using this condition/rule to eliminate trailing slashes (or rather: rewrite to the non-trailing-slash-URL, by a 301 redirect; I'm doing this to avoid duplicate content and because I like URLs with no trailing slashes better):
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{HTTP_HOST} !^\.localhost$ [NC] RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]
Working well so far. Only drawback:
it also forwards "multiple-trailing-slash"-URLs to non-trailing-slash-URLs.
Example:http://example.tld/foo/bar//////
forwards to http://example.tld/foo/bar
while I only want http://example.tld/foo/bar/
to forward to http://example.tld/foo/bar
.
So, is it possible to only eliminate trailing slashes if it's actually just one trailing slash?
Sorry if this is a somewhat annoying or weird question!
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
以下规则将匹配任何以斜杠结尾的 URL,并删除其末尾的所有斜杠:
注意: 当前接受的答案仅适用于 http 而不是 https,但此答案适用于两者。
the following rule will match any URL ending in a slash and remove all slashes from the end of it:
Note: The currently accepted answer only works for http not https but this one works for both.
将重写规则更改为:
英文:匹配字符串的开头、一个或多个任何内容,而不是斜杠、斜杠、结尾。
change the rewrite rule to:
in English: match the start of the string, one or more anything, NOT a slash, a slash, the end.
这是一个基于 mod-alias 的解决方案,用于从 url 中删除尾部斜杠:
您可以在 htaccess 或 server.config 文件中使用上述重定向。
这会将 /uri/ 重定向到 */uri** 。
Here is a mod-alias based solution to remove trailing slash from urls :
You can use the above Redirect in your htaccess or server.config file.
This will redirect /uri/ to */uri** .
即最前面的字符不能是斜杠。
I.e. the forelast character must not be a slash.
如果您只想从 GET 请求中删除尾部斜杠,请使用以下命令:
If you only want to remove the trailing slashes from GET requests, use the below: