ryerye ryerye - 1 month ago 5
Apache Configuration Question

Redirect all non-www to www for both http and https with .htaccess

I want to redirect all non-www to www - if the request is through http it should redirect to http://www.domain.com, if the request is through https then direct to https://www.domain.com

I have tried the following in my .htaccess, but it redirects everything to https

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

Answer

You can use this rule as your first rule:

RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTPS}s on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Comments