How to make sure your website is always accessed via its www-domain name variant
Redirection using .htaccess (Apache)
If you want to make sure everybody who wants to access your site comes to it by using the www-name, then add the following to your .htaccess file:
# Redirect to www Options +FollowSymLinks
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$ [NC] RewriteCond %{HTTPS}s ^on(s)| RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
These rules work for both HTTP and HTTPS. Save your file to its original place and your done! Oh yes, and don't forget to check if everything works the way you intended.
Explanation
- Comment line to indicate in your .htaccess file why you have added this part
- This line is an Apache directive (prerequisite for mod_rewrite)
- This line makes sure you can use the rewrite features of Apache (enables mod_rewrite)
- This line sets the basic directory for your rewrites to the root directory of your site
- This line checks if you have provided a correct domainname.tld combination with 2 parts in it (so it detects the www is lacking) - the URL starts with 1 or more characters different from a dot, followed by exactly 1 dot, followed by 1 or more character different from a dot. The $ indicates that this is the end of the regular expression, so it will only catch your domain name, all extra parts of the URL will not be affected. [NC] indicates that the regular expression has to be checked case insensitive
- This line checks whether you are using http or https
- This line does the actual rewrite of your original URL to ensure it contains "www." at the start of the URL. R=301 indicates that this URL is permanently moved, L indicates it is the last rule that will be processed for redirection of this kind of input which meets the rewrite conditions
Notes:
- If you already have "Options +FollowSymLinks" defined somewhere earlier in your .htaccess file, then there is no need to declare it here for a second time
- Same goes for "RewriteEngine On": if it's already defined earlier in your .htaccess file, you don't have to add it for a second time
- Same goes for "RewriteBase /": if it's already defined earlier in your .htaccess file, you don't have to add it for a second time