3

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.

3
  • What is your website built with? it's possible the website is trying to do the opposite (always adding trailing slash), hence the redirect loop..
    – Ben
    Oct 11, 2012 at 1:29
  • It's a custom tailored website where I code everything from scratch, having full control. Other rules on the .htaccess file apply only to specific pages... this leads me to conclude the problematic line in htaccess is that one with [R=301,L]
    – Afonso Gomes
    Oct 11, 2012 at 1:35
  • 2
    Whoever said that removing the trailing slash had any effect on SEO was smoking something illegal and needs to share. Oct 13, 2012 at 23:42

2 Answers 2

2

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] 
0
4

You should probably look at the documentation for mod_dir

A "trailing slash" redirect is issued when the server receives a request for a URL http://servername/foo/dirname where dirname is a directory. Directories require a trailing slash, so mod_dir issues a redirect to http://servername/foo/dirname/.

This module is probably adding a slash again after you removed it, etc. etc. You can disable that behaviour using the DirectorySlash directive.

You must log in to answer this question.