Reputation: 9696
I am trying to create a rule where a trailing slash is added automatically if the URL path points to a folder / directory and not a file. For example the images folder:
http://example.com/images
to become
http://example.com/images/
Somehow some browsers do this automatically but I need my server to handle it first through my rules. On the other hand I have rules that redirect certain URLS to a file for example:
http://example.com/home
gets opened by
http://example.com/index.php?page=home
So in this case I don't want to add the trailing slash since home points to a file and http://example.com/home/
with a trailing slash will just redirect to a not found page.
Here is what I have so far but I get a 500 error:
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule (.*)$ /$1/ [QSA]
RewriteRule .* - [L]
To my understanding RewriteCond %{REQUEST_FILENAME} -d
checks and applies all the following rules if the URL is a folder/directory.
Then with RewriteRule (.*)$ /$1/ [QSA]
I am trying to add a slash at the end and also allow any query string to sent, I believe here is where I have my error, finally I understand that RewriteRule .* - [L]
stops checking if the URL is a directory and lets the rest of the rules work normal.
Any ideas? Thanks
Upvotes: 2
Views: 1865
Reputation: 41219
You get an infinite loop error from the code
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule (.*)$ /$1/ [QSA]
Because the pattern also matches the target, and on the second iteration /dir/ rewrites to /dir/ causing the loop error.
You need a RewriteCond to prevent this
Try :
RewriteCond %{REQUEST_URI} !/$
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule (.*)$ /$1/ [L,R]
RewriteCond %{REQUEST_URI} !/$ says "Dont redirect /foo/ to /foo/
Upvotes: 2