0

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?

1 Answer 1

1

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.

3
  • 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? Oct 26, 2009 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, 2009 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. Oct 26, 2009 at 18:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .