Getting RewriteCond directory flag to work without trailing slash

apache-2.2mod-rewrite

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?

Best Answer

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.

Related Topic