URL Rewrite Including Trailing Slash If Not Present

我的梦境 提交于 2019-12-11 00:26:48

问题


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/index.php
RewriteRule ^/my/path/(.*[^/])$ $1/ [R,L]

Any Ideas or solutions?


回答1:


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]


来源:https://stackoverflow.com/questions/5120866/url-rewrite-including-trailing-slash-if-not-present

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!