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'm trying to detect existing directories, supporting both with and without a trailing slash in the URL but without doing a redirect for missing slashes. Here are the rules:

  RewriteCond /home/user/public_html%{REQUEST_URI} -d
  RewriteRule ^ /home/user/public_html%{REQUEST_URI} [L]
  RewriteCond /home/user/public_html%{REQUEST_URI}/ -d
  RewriteRule ^ /home/user/public_html%{REQUEST_URI}/ [L]

The first rule works fine when the URL contains a trailing slash, but the second rule doesn't work for no trailing slash (e.g. /foobar/ works but /foobar doesn't).

How can I set this up without doing a 30x redirect?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

You could use both rules at the same time, like this:

# Rewrite sites with trailing slash this way...
RewriteCond %{REQUEST_URI} ^.*\/$
RewriteCond /home/user/public_html%{REQUEST_URI} -d
RewriteRule ^ /home/user/public_html%{REQUEST_URI} [L]

# Rewrite sites without trailing slash this way...
RewriteCond %{REQUEST_URI} ^.*[^\/]$
RewriteCond /home/user/public_html%{REQUEST_URI}/ -d
RewriteRule ^ /home/user/public_html%{REQUEST_URI}/ [L]

Those regexps are from my head and have not been tested. And I haven't had my coffee yet.

share|improve this answer
    
I don't see how this differs in it's behaviour from my original solution, it just adds a check for trailing slash first so the -d check won't be executed if URI isn't matched (as opposed to mine were they would always both be executed). Perhaps I'm missing something? –  Rory Fitzpatrick Oct 26 '09 at 17:37
    
Your first rule only does "If this is a directory, then do this." On most systems, /path/to/my/webroot/subdir and /path/to/my/webroot/subdir/ are directories. Therefor, it's likely to always hit your first rule and never hit your second rule. –  Kyle Smith Oct 26 '09 at 17:54
    
I think I understand, you mean the first RewriteCond was matching but the RewriteRule didn't function correctly? Either way, I found reversing the rules worked fine which I think basically does the same thing. –  Rory Fitzpatrick Oct 26 '09 at 18:55

Your Answer

 
discard

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.