开发者

URL Rewrite Including Trailing Slash If Not Present

I've got this RewriteRule to work.

RewriteBase /my/path/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /my/path/index.php [L]

So URLs with a trailing slash work. http://localhost/my/path/foo/bar/

The problem is that URLs without the trailing slash will break relative links. Plus it dosen't look good.

This reaches the maximum number of internal redirects.

RewriteRule ^/my/path/(.*[^/])$ $1/ [R]
RewriteRule . /my/path/index.php [L]

And this will do... http://localhost/my/path/index.php/bar/

RewriteRule . /my/path/开发者_如何学Goindex.php
RewriteRule ^/my/path/(.*[^/])$ $1/ [R,L]

Any Ideas or solutions?


The confusing feature of mod_rewrite is that, after an internal redirect, even one qualified with [L], the entire set of rules is processed again from the beginning.

So you redirect a nonexistent path to index.php, but then the rules for adding a slash kick in and you don't get the result you want.

In your case you simply need to put the file nonexistence condition on both of the redirect rules:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule [^/]$ %{REQUEST_URI}/ [L,R]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ /my/path/index.php [L]

Or maybe move this condition to the top of the file:

RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]   # redirect to same location to stop processing

RewriteRule [^/]$ %{REQUEST_URI}/ [L,R]

RewriteRule ^ /my/path/index.php [L]

There's also an undocumented trick to stop processing after an internal redirect which should make more complex rulesets easier to write – using the REDIRECT_STATUS environment variable, which is set after an internal redirect:

RewriteCond %{ENV:REDIRECT_STATUS} .  # <-- that's a dot there
RewriteRule ^ - [L]   # redirect to same location to stop processing

RewriteRule [^/]$ %{REQUEST_URI}/ [L,R]

RewriteRule ^ /my/path/index.php [L]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜