I have seen several questions on this with varying responses. I’m using a WordPress website and want to force a trailing slash. From various sources I have found these two options:
Option 1
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1/ [L,R=301]
Option 2
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteCond %{REQUEST_FILENAME} !.(gif|jpg|png|jpeg|css|js)$ [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1/ [L,R=301]
Can someone comment on the functional difference (which one should I use)? I’m not clear if the 2nd and 4th conditions Option 2 add are necessary (if it’s not a file, it wouldn’t be a gif/jpg/png/etc right? and if it doesn’t have a trailing slash, won’t it always be true it’s not a directory?).
I’m also trying to figure out where in my htaccess I should put it. I currently have the following in my htaccess in this order
- http:https redirect
- caching stuff (via wp-rocket plugin)
- deny access to wp-config
- whitelist IPs that can access wp-login
- AMP redirects (removes /amp and /amp/)
- maybe add the trailing slash ruleset here?
- post slug redirects (duplicate posts, slug changes)
- old URL format redirects (remove date in URL)
- default WordPress rule (permalink thing)
- disable directory browsing
Thanks everyone for your help and expertise!
Read more here: Options to Force Trailing Slash in htaccess