ryerye ryerye - 1 month ago 6
HTTP Question

htaccess rewrite http://example.com to http://www.example.com but https://www.example.com to https://example.com

Using .htaccess rewrite, I'd like to have:

http://example.com
redirect to:
http://www.example.com

https://www.example.com
redirect to:
https://example.com


Which is the best way to do this?

I've started with:

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

Answer

You need 2 rules:

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.+)$
RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
Comments