Wednesday, January 10, 2018

How to redirect from non-www to www in Apache

In this post I will show you how to redirect from one site to another in apache. Actually, it's pretty easy to do. But let's learn it by example.

Two sites: site.com and www.site.com.

Apache config looks like this /etc/apache2/sites-available/site.conf:
<VirtualHost *:80>
  ServerName site.com
  DocumentRoot /var/www/site
</VirtualHost>
So both sites can be loaded independently, but there is no redirect.

Task: when you open site.com, it should redirect you to wwww.site.com. And when you open www.site.com, it should work as normal.

Let's do it.

1. Open the same apache config and instead of one VirtualHost, we need to make two:
<VirtualHost *:80>
  ServerName www.site.com
  DocumentRoot /var/www/site
</VirtualHost>

<VirtualHost *:80>
  ServerName site.com
  Redirect / http://www.site.com
</VirtualHost>
Here the first entry is for www.site.com, second entry - for redirection from site.com to www.site.com

2. For the changes to take effect, you should reload apache:
sudo service apache2 reload

That's it. Now it does what it should. But if you're still not sure what all this means, you can watch this video:



Or just drop a comment below. Good luck!

No comments:

Post a Comment