mod_rewrite: remove trailing slash (only one!)
Solution 1
the following rule will match any URL ending in a slash and remove all slashes from the end of it:
RewriteRule ^(.*)/+$ $1 [R=301,L]
Note: The currently accepted answer only works for http not https but this one works for both.
Solution 2
change the rewrite rule to:
RewriteRule ^(.+[^/])/$ http://%{HTTP_HOST}/$1 [R=301,L]
in English: match the start of the string, one or more anything, NOT a slash, a slash, the end.
Solution 3
Here is a mod-alias based solution to remove trailing slash from urls :
RedirectMatch ^/(.*?)/$ /$1
You can use the above Redirect in your htaccess or server.config file.
This will redirect /uri/ to */uri** .
Solution 4
^(.+[^/])/$
I.e. the forelast character must not be a slash.
user367217
Updated on October 10, 2020Comments
-
user367217 over 3 years
I use mod_rewrite/.htaccess for pretty URLs.
I'm using this condition/rule to eliminate trailing slashes (or rather: rewrite to the non-trailing-slash-URL, by a 301 redirect; I'm doing this to avoid duplicate content and because I like URLs with no trailing slashes better):
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{HTTP_HOST} !^\.localhost$ [NC] RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]
Working well so far. Only drawback:
it also forwards "multiple-trailing-slash"-URLs to non-trailing-slash-URLs.Example:
http://example.tld/foo/bar//////
forwards tohttp://example.tld/foo/bar
while I only wanthttp://example.tld/foo/bar/
to forward tohttp://example.tld/foo/bar
.So, is it possible to only eliminate trailing slashes if it's actually just one trailing slash?
Sorry if this is a somewhat annoying or weird question!
Thanks.
-
Ujjwal Singh almost 8 yearsSame question: stackoverflow.com/questions/19990838/…
-
-
nickhar almost 11 years@steve The completed answer is obviously going to be worth the wait.
-
Amir Ali Akbari over 9 yearsIt seems that the
http://%{HTTP_HOST}/$1
should behttp://%{HTTP_HOST}$1
otherwise an extra / is added to the beginning of new url. -
Just Lucky Really almost 9 yearsI've refreshed this page for over 2 years now waiting for the answer ... This is the literally the last thing I need to do before putting my website live ...
-
aleemb almost 9 yearsJust noticed this today after so long. Maybe I should not have clarified to humour the other readers :)
-
ironchicken over 7 yearsThe regex should match at least one character before
/
, so\(.+)/+$
, otherwise you get an infinite redirect loop when requesting/
. -
Daniel Dewhurst over 6 yearsThis worked for me, aleemb's answer didn't work as I'm using virtual hosts.