mod_rewrite: add trailing slash?

强颜欢笑 提交于 2019-12-18 13:14:26

问题


I am using a .htaccess file to direct requests for a directory to a custom php file that provides info about that directory (and i want the url displayed by the browser to not change).

Here is the relevant part of the .htaccess file.

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ /myphp.php?url=%{REQUEST_URI} [QSA,L] 

This works well if you go to a directory and include a trailing slash:

http://domain.com/path/

But without the trailing slash, it doesn't

http://domain.com/path

The url (shown in the browser) turns into:

http://localhost:8888/path/?url=/path

I've tried fixing this by adding a rule above this rule:

RewriteCond %{REQUEST_FILENAME} -D
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ $1/ [L]

But that isn't working for me.

How can I get .htaccess to add the trailing slash if it is omitted and then act just as if it had been there?

Thank you

Update: As requested, here is the whole thing.

<IfModule mod_rewrite.c>
RewriteEngine On

#force trailing slashes on real directories
RewriteCond %{REQUEST_FILENAME} -D
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ $1/ [L]

#use the directory viewer on directories without an index page
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*)$ /myphp.php?url=%{REQUEST_URI} [QSA,L]  

</IfModule>

回答1:


This line:

RewriteCond %{REQUEST_FILENAME} -D

Should have been:

RewriteCond %{REQUEST_FILENAME} -d



回答2:


Don't bother with Mod Rewrite, there is a directive for it

<Location /some/path>
  DirectorySlash On
  SetHandler some-handler
</Location>

http://httpd.apache.org/docs/2.2/mod/mod_dir.html




回答3:


Did you mean

RewriteRule ^(.*)$ $1/ [L]

instead?

I don't know about your approach. I would try something like

RewriteRule ^/(\S+)/?$ /myphp.php?url=$1

I've used this for rewriting before and it works:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain\.com
RewriteRule ^(.*)$ http://www.domain.com$1
RewriteRule ^/(\S+)/?$ /myphp.php?url=$1

Note that I didn't include the trailing slash in the first rule.

Also, I would advice you not to rely on .htaccess unless absolutely necessary. This is because the server will check for .htaccess files constantly. Using the httpd.conf file instead means apache will only load conditions and rules once. At least I was adviced to do so because of this.




回答4:


Try this. It will add trailing slash to directory requests which don't have trailing slash.

<IfModule mod_rewrite.c>
RewriteEngine On

#use the directory viewer on directories without an index page
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.*?)/?$ /myphp.php?url=$1/ [QSA,L]  

</IfModule>


来源:https://stackoverflow.com/questions/3133111/mod-rewrite-add-trailing-slash

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