After you have set-up your website, you may notice that even if you type in www.example.com, the web address appears as example.com. Where did the www go? The configuration does not exist on your DNS provider! The setting actually is in a file called .htaccess
on the root or top level of your web pages.
For example, our website, slothparadise, runs on an Amazon Web Services EC2 instance where the web files are kept inside apache’s /var/www/html
directory.
Usually when you create a website, you’ll also create a .htaccess
file. If you don’t have the file, you can open it with any text editor inside /var/www/html
.
Redirect http no www to www page
First, we will open our .htaccess
file inside /var/www/html
or wherever the top level of your web page files are. Vim is used for editing files.
vim .htaccess
We want to redirect all of our non www pages to www pages.
1 2 3 | RewriteEngine On RewriteCond %{HTTP_HOST} !^www\. RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L] |
After saving the file, you can restart your web server. On apache for Ubuntu machines, you would use:
sudo /etc/init.d/apache2 restart
Restarting apache’s web server will change all the http no www links to www. Whenever someone visits example.com, they will visit www.example.com instead.
Why you should do this
- Duplicate content on Google or other search engines pops up when you do not explicitly redirect to either all www or no www. Usually, this unfortunately hurts you and puts your website down in the search ranking.
- Some people visit www.example.com. Some people visit example.com. The search points are split!
- I personally like having www on the website. For years, most people can say that www is the heart of what makes the Internet the Internet
Redirect www to no www pages
If you want the other way around, the positivity on your website occurs the same way because traffic will direct towards only one possible combination.
vim .htaccess
After opening the file, include the following lines.
1 2 3 | RewriteEngine On RewriteCond %{HTTP_HOST} !^example\.com$ [NC] RewriteRule ^(.*)$ http://example.com/$1 [R=301,L] |
After saving the file, you can restart your web server. On apache for Ubuntu machines, you would use:
sudo /etc/init.d/apache2 restart
Now, all www.example.com page links will redirect to example.com.