htaccess force https and redirect www to non-www, but no other subdomains

I found most of the suggestions were not catching when you had something that was https://www.example.com and redirecting to https://example.com.

The following worked for all permutations:

RewriteEngine On

# match any URL with www and rewrite it to https without the www
RewriteCond %{HTTP_HOST} ^(www\.)(.*) [NC]
RewriteRule (.*) https://%2%{REQUEST_URI} [L,R=301]

# match urls that are non https (without the www)
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^(www\.)(.*) [NC]
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Hope this helps someone!

Leave a Comment