How to redirect a URL without www to a normal URL
This tutorial will show you several ways on how to redirect an URL without any www at the beginning.
For example, you go to:
mywebsite.com
You'll be redirected to:
www.mywebsite.com
I'll show you how to do this using .htaccess file, and then using conf files.
Redirection using .htaccess
- Go to your www/ directory.
- Create or open a .htaccess file.
- Type this, replacing the example domain name by yours:
RewriteEngine on RewriteCond %{HTTP_HOST} !^www\.mywebsite\.com(:80)?$ RewriteRule ^/(.*) http://www\.mywebsite\.com/$1 [L,R=301] - This will do a 301 Redirection, which is the HTTP code for "301 Permanently moved". So that you don't get a duplicate site on Google (one with www, one without).
- No need to restart Apache.
- If this does not work, try the method using conf files.
Redirection using *.conf files
- Go to your apache directory (might be /etc/apache2, or otherwise try 'find / -type d -name 'apache2' to search for it).
- You'll have to look into those files to find your virtual host configuration:
/etc/apache2/httpd.conf /etc/apache2/sites-available/default /etc/apache2/sites-available/*.conf
- When you have it, you should see something like this (this can be a lot bigger sometimes):
<VirtualHost 218.0.101.14:80> DocumentRoot /home/mywebsite/www ServerName mywebsite.com ServerAlias www.mywebsite.com <Directory "/home/mywebsite/www"> Order Deny,Allow Allow from all AllowOverride All </Directory> </VirtualHost> - Add those lines, before the </VirtualHost> tag:
RewriteEngine on RewriteCond %{HTTP_HOST} !^www\.mywebsite\.com(:80)?$ RewriteRule ^/(.*) http://www\.mywebsite\.com/$1 [L,R=301] - This should look like this:
<VirtualHost 218.0.101.14:80> DocumentRoot /home/mywebsite/www ServerName mywebsite.com ServerAlias www.mywebsite.com <Directory "/home/mywebsite/www"> Order Deny,Allow Allow from all AllowOverride All </Directory> RewriteEngine on RewriteCond %{HTTP_HOST} !^www\.mywebsite\.com(:80)?$ RewriteRule ^/(.*) http://www\.mywebsite\.com/$1 [L,R=301] </VirtualHost> - Save, and restart apache.
sudo /etc/init.d/apache2 restart
- This should do it!

























