Forwarding with .htaccess: HTTPS, with and without "www"

Forwarding with .htaccess: HTTPS, with and without www

Forward from www to www without www

For search engines it is relevant that the page owner chooses a version with which his website is found. So the question is, with www or without www? From SEO perspective this decision is not important, but should be made anyway, because otherwise you run the risk that pages are classified as Duplicate Content and lose your ranking.

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

The snippet does the following: It first checks if a www has been entered or not. If none was entered, it will be added. The second condition checks if the address was called with the http protocol, if this is the case it will be forwarded to the https variant.

The whole thing works without a hardcounted domain, by the way. This is especially advantageous if you have a second top-level domain on which, for example, the English version of the website is to be displayed. Then you don't have to add anything anymore.

Forward from www to www without www

If you prefer the variant without www, you only have to adapt the following part.

RewriteEngine On
**RewriteCond %{HTTP_HOST} ^www\. [NC]
**RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]

Watch cache

Browsers and sometimes routers remember a few things that make it difficult to test .htaccess files for performance reasons. Should something not work: Try it again in your browser's incognito mode and if it doesn't work, a router restart might help as well.

You also have to pay attention to the domain server configuration. A simple CNAME record is nice, but it is never forwarded from the without www variant to the with www variant, because the server is never reached to execute the .htaccess at all, so: CNAME and A Record (or AAAA for IPv6).

Leave a like or comment (~‾▿‾)~
Name Text