Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

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.

share|improve this question

migrated from stackoverflow.com Oct 11 '12 at 9:54

This question came from our site for professional and enthusiast programmers.

    
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 '12 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 '12 at 1:35
2  
Whoever said that removing the trailing slash had any effect on SEO was smoking something illegal and needs to share. –  Michael Hampton Oct 13 '12 at 23:42

2 Answers 2

up vote 2 down vote accepted

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] 
share|improve this answer
    
Worked like a charm! Thanks @Robbie –  Afonso Gomes Oct 11 '12 at 2:28

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.