htaccess rules to enforce SSL (https) and remove/add www before the domain name

This is an archive post. It will not be updated.

If you rewrite domains from www.example.com to example.com (or vice versa), the SSL certificate must be valid for both domain variants, or you need two separate SSL certificates.

Also keep in mind that some browsers have a very aggressive cache. So clear your browser cache before testing new settings.

Option 1:
Enforce https and remove www before the domain name

If you want this code to also run in a subfolder without the subfolder part of the address getting lost during the rewrites, you need to add a separate .htaccess file in the subfolder and enter this slightly modified code for the subfolder in it.

RewriteEngine On
# Redirect domain name with www to the variant without www
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ https://%1/$1 [L,R=301]
# Always enforce https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Option 1:
Adapted code for subfolders

Add a separate .htaccess file with this code to the subfolder. Replace the name “beispielordner” with the name of your folder.

#htaccess variant located in the subfolder “beispielordner”
RewriteEngine On
# Redirect domain name with www to the variant without www in the subfolder “beispielordner”
RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
RewriteRule ^(.*)$ https://%1/beispielordner/$1 [L,R=301]
# Always enforce https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Option 2:
Enforce https and add www before the domain name

RewriteEngine On
# Redirect domain name without www to the variant with www
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Always enforce https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]