I'd like to reduce the redirect chains currently I'm dealing with by directly redirecting the URLs from the old domain that ends with a trailing slash to the new domain without a trailing slash.
My current setup does like this:
olddomain.com/page redirects to newdomain.com/page (this is OK)
However, if the user enters olddomain.com/page/ it first redirects to newdomain.com/page/ and then to newdomain.com/page
What I want is to directly redirect olddomain.com/page/ to newdomain.com/page
My .htaccess:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^olddomain.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.olddomain.com
RewriteRule (.*)$ https://newdomain.com/$1 [R=301,L,NC]
</IfModule>
Thank you!
CodePudding user response:
RewriteRule (.*)$ https://newdomain.com/$1 [R=301,L,NC]
If the source URLs may or may not contain a trailing slash, but always redirect to the URL without a trailing slash then make the trailing slash optional in the RewriteRule
pattern, but importantly you need to make the *
quantifier non-greedy so it does not consume the trailing slash (since the greedy *
quantifier will take priority over the optional token that follows).
For example:
RewriteRule (.*?)/?$ https://newdomain.com/$1 [R=301,L]
The *?
quantifier makes it non-greedy, so it consumes as least as possible.
The NC
flag is redundant here since the pattern (.*?)/?$
is effectively case-insensitive anyway.