By using this site you agree to the use of cookies.

Learn more

Share via:


Redirect From WWW to non-WWW and Vise Versa

Redirecting to non-WWW from WWW is done easily using either Apache configuration files or htaccess, which to use depends on your circumstances.

Edited: 2018-02-17 02:23

Beamtic article image

Choosing either the non-www or www version of your website is fairly important, since having both can lead to problems for your users. Redirecting is not as important as it used to be, but some may still choose to have a redirect in place. The important thing is that your site is not accessible on both the www and the bare domain.

The easiest way to redirect your site with Apache is to maintain a .conf file for each version of your site. Those files should be placed in /etc/apache2/sites-available/ as separate .conf files, and enabled with the a2ensite command.

The content of the configuration file should look like the below:

<VirtualHost *:80>
    Redirect permanent /

This is a very simple configuration file for a Virtual Host, it is expected you already have one to handle the bare domain. This will only handle the www subdomain of, and redirect traffic to the non-www version. You can easily do it the other way around, if needed.

To create the file, a tool such as nano may be used from the terminal (sudo nano www_example_com.conf). After creating the file, you can enable the site with sudo a2ensite www_example_com.conf. Finally, remember to run sudo service apache2 reload.

Another option is to use a .htaccess file, but chances are you will still need the VHOST file anyway.

Sometimes servers might have errors in their configuration, allowing people to access the non-HTTPS version, and this can in rare cases lead to security problems. So, it is really important you setup your redirects correctly when using HTTPS. Subdomains are treated as separate sites, and should therefor have each their own Virtual Host file (.conf file in /etc/apache2/sites-available/). You can also have multiple virtual hosts in the same configuration file, but this is not recommended, since it might not be compatible with certain tools (I.e. letsencrypt).

Redirecting WWW to non-WWW with htaccess

Since the www part is just a sub-domain many prefer not to use it. So, unless you have a technical reason to use WWW, we recommend just using the bare domain. I.e.

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

The R=301 part creates a 301 "moved permanently" redirect, while the L makes it the last rule – preventing more rules from being executed.

In case you want to redirect to www instead, you may use the below:

You can also redirect your bare domain to your WWW subdomain – though this is likely less desirable.

RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$$1 [L,R=301]

You only need to enable the RewriteEngine with RewriteEngine On once in your .htaccess file.