mod_rewrite的:删除斜线(只有一个!)斜线、只有一个、mod_rewrite

由网友(笑魇醉看)分享简介:我使用mod_rewrite /的.htaccess为pretty的网址。I use mod_rewrite/.htaccess for pretty URLs.我用这个条件/规则,以消除拖尾斜杠(或者说:改写到非尾随斜杠的URL,通过301重定向,我这样做是为了避免重复的内容,而且因为我喜欢和网址没有尾随斜线越好...

我使用mod_rewrite /的.htaccess为pretty的网址。

I use mod_rewrite/.htaccess for pretty URLs.

我用这个条件/规则,以消除拖尾斜杠(或者说:改写到非尾随斜杠的URL,通过301重定向,我这样做是为了避免重复的内容,而且因为我喜欢和网址没有尾随斜线越好):

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]

工作很顺利。唯一的缺点: 它也转发多尾随斜杠-URLs 的到的无拖尾斜杠网址的。

Working well so far. Only drawback: it also forwards "multiple-trailing-slash"-URLs to non-trailing-slash-URLs.

例: 的http://example.tld/foo/bar////// 转发到的http://example.tld/foo/bar 而我只想的http://example.tld/foo/bar/ 转发到的http://example.tld/foo/bar

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!

感谢。

推荐答案

修改重写规则:

RewriteRule ^(.+[^/])/$ http://%{HTTP_HOST}/$1 [R=301,L]

在英语:匹配字符串,一个或多个任何东西,不是一个斜线,斜线,结束的开始

in English: match the start of the string, one or more anything, NOT a slash, a slash, the end.