Redirect domain always to subdomain (eg. www) in .htaccess

You might want to redirect your website always to www and avoid duplicate content on search engines by providing your website by both domain and www-subdomain. 

RewriteEngine On

RewriteCond %{HTTP_HOST} ^$
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=302]

line by line explanation

RewriteEngine On

If the rewrite module on your apache web server is not yet enabled, you will do now for this request. You could also put all lines into <IfModule></IfModule> for checking if the rewrite module is available at all on your web server. Nowadays this should not be necessary any longer, since rewriting urls is a usual requirement for most applications. 

<IfModule mod_rewrite.c>
 # all lines from above
RewriteCond %{HTTP_HOST} ^$

This line contains of three parts:

  • RewriteCond which means, we are specifying now a condition which must be met for executing the RewriteRule.
  • %{HTTP_HOST} is the variable, automatically provided by apache, which is to be checked.
  • ^$ is the value the variable – in this case the HTTP_HOST – must have. The value can be described as a regex (regular expression). ^ means beginning of string, $ end of string, thus the HTTP_HOST must be precisely equal to “”. 
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=302]

 This line contains of four parts:

  • RewriteRule telling the apache the rewrite rule which should be executed, when the rewrite conditions are met
  • ^(.*)$ the second part determines for which request paths the rule should be executed, again as a regular expression. 
  • https://www.%{HTTP_HOST}%{REQUEST_URI} is the destination of the rewriting. You can use apache variables in there like HTTP_HOST or REQUEST_URI. 
  • [R=302] is an optional flag. We are setting the redirect flag with the HTTP status code for permanent redirects. 

Of course the explanation above was a short simplified version – more details can be found in the apache documentation for the mod_rewrite module. The documentation for rewrite flags could be also interesting to read.