Php – mod_rewrite remove trailing slash is causing loops

.htaccessapache-2.2mod-rewritePHP

I have a site using mod_rewrite to make pretty URLs … everywhere I read the removing the trailing slash is good for SEO and therefore I went with the rule:

RewriteRule ^(.+)/$ /$1 [R=301,L]

I think the 301 redirect might impact performance but that's not my question…

The thing is that removing the trailing slash is causing me a loop when I try to access the index.php of a EXISTING subdirectory like so: http://mysite.com/a-real/directory/

To my understanding, mod_rewrite atempts to remove the trailing slash but in this case it wasn't suppose to.

How can I fix this? I'm betting that's a fairly simple solution however beyond my knowledge.

Best Answer

The simplest solution to this will probably be to tell the .htaccess not to redirect if the file or directory exists

Add the following two lines to the condition to prevent this

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f

(You can also add -l if you use symlinked directories / files)

Also, as you suggest, drop the 301, so your full htaccess will be:

Options +FollowSymLinks
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^(.+)/$ /$1 [L]