Blackbam
Blackbam

Reputation: 19386

Apache .htaccess: How to add missing trailing slash to URLs but ignore files and special URLs?

As my web project sometimes throws 404s if trailing slashes are missing I always want my server to add trailing slashes to the URLs. Therefore I have used the following pattern in .htaccess:

# ################################## #
#      Redirect URLs which are not files to their trailing slash equivalent #
# ################################## #
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)([^/])$ /$1$2/ [L,R=301]

It looked fine but then I realized that links like

http://www.my-awesome-website.com/theme/base.css?ver=1995

were converting to

http://www.my-awesome-website.com/theme/base.css/?ver=1995

Which is obviously undesirable and makes the website break. How do I have to rewrite this rule such that any requests for files (.php, .jpg, .html, etc.) are for sure not included?

Upvotes: 1

Views: 507

Answers (1)

anubhava
anubhava

Reputation: 785571

You can try this rule (assuming you don't have dot in your non-file requests):

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)([^./])$ %{REQUEST_URI}/ [L,R=301,NE]

Make sure to test this in a new browser to avoid old cache.

Upvotes: 2

Related Questions