Apache 2 Redirects For "non-www" Sub-domains To "www"
Introduction
When you visit https://vultr.com, you'll notice it automatically forwards you to its "www" subdomain http://www.vultr.com. This writeup shows you how to setup Apache 2 to redirect a non-www sub-domain to a "www" one, and vice-versa.
Pre-requisites
- You have a Vultr Linux instance running Apache 2.
- Your have domain name (e.g example.com) whose DNS A records for "@" and "www" are pointing to the IP of your Vultr machine above.
Setup to redirect "non-www" to "www"
Method 1: Using a 301 redirect
Setup two virtual hosts, one for the "non-www" sub-domain and the other for "www"
<VirtualHost *:80>
ServerName example.com
Redirect 301 / http://www.example.com/
</VirtualHost>
<VirtualHost *:80>
ServerName www.example.com
#other vhost settings go here (e.g. logs, site root)
</VirtualHost>
Method 2: Using a rewrite engine condition
Put below snippet in a .htaccess file in your site's root folder. Note that Apache's mod_rewrite module has to be enabled for you to use this method. You can enable it by running sudo a2enmod rewrite
.
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
Setup to redirect "www" to "non-www"
Method 1: Using a 301 redirect
Setup two virtual hosts, one for the "www" sub-domain and the other for "non-www"
<VirtualHost *:80>
ServerName www.example.com
Redirect 301 / http://example.com/
</VirtualHost>
<VirtualHost *:80>
ServerName example.com
#other vhost settings go here (e.g. logs, site root)
</VirtualHost>
Method 2: Using a rewrite engine condition
Put below snippet in a .htaccess file in your site's root folder. Note that Apache's mod_rewrite module has to be enabled for you to use this method. You can enable it by running sudo a2enmod rewrite
.
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]