I have the following code in my htaccess file:
# Force Trailing Slash RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^[^/]+$ %{REQUEST_URI}/ [L,R=301]
That seems to work fine when I go to www.mydomain.com/test it redirects it to /test/. The problem is when I go to www.mydomain.com/test/another it doesn't put the trailing slash on another.
Does anyone know how to modify my code to make the trailing slash work no matter how long the URL is?
Thanks!
How to add a trailing slash to URLs. One of the easiest and most convenient way to add or enforce trailing slashes on URLs is by RewriteRule directive. You can write a single rule in your htaccess file that will apply to all URLs without a trailing slash.
To do so, go to the “Settings -> Permalinks” section and, depending on your situation, either add or delete the last slash. The “Custom Structure” field ends with a slash, so all other WordPress URLs will have the trailing slash. Likewise, if it is not present there, the slash will be missing in your website's URLs.
replace(/\/+$/, '') . The replace method will remove the trailing slash from the string by replacing it with an empty string.
A slightly more robust answer, based on the answer above:
RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^(.*)([^/])$ /$1$2/ [L,R=301]
The RewriteCond
will check to make sure there's no files with that name, and if not, perform the RewriteRule. More future-proof than having a manual list of extensions!
RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301]
Edit: in the case you want to exclude some requests like for php files:
RewriteCond %{REQUEST_URI} !\.(php|html?|jpg|gif)$ RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With