Kathir Sid Vel Kathir Sid Vel - 1 year ago 81
Apache Configuration Question

HTACCESS 301 Redirect Rule to point all URL Variations to the Live URL

I am trying to achieve something which is working 99%, but there is a tiny issue.

Let's say my live URL is https://www.example.com/sample-page/

I want all the following URL variations to redirect to the live URL with a 301 status.


All of the above should redirect to https://www.example.com/sample-page/

I managed to get this working by using the htaccess rule displayed below.

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

The problem with the above rule is this: http://example.com/sample-page/ does a double redirect.

301 Moved Permanently
301 Moved Permanently
200 OK

As you can see, http redirects to https and then https non-www redirects to https www. I have been trying a few tweaks to this rule and reading up, but I am sure someone here would have a quicker and more robust solution?

Answer Source

You can use this single rule to redirect http -> https and add www and there is no need to hardcode host name in the rule:

RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [L,R=301,NE]

You can also reorder your existing rules and avoid multiple redirects like this:

# first add www and make sure it is https://
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]

# http -> https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]