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

  1. Go to your www/ directory.
  2. Create or open a .htaccess file.
  3. 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]
  4. 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).
  5. No need to restart Apache.
  6. If this does not work, try the method using conf files.

Redirection using *.conf files

  1. Go to your apache directory (might be /etc/apache2, or otherwise try ‘find / -type d -name ‘apache2’ to search for it).
  2. 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
  3. 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>
  4. 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]
  5. 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>
  6. Save, and restart apache.
    sudo /etc/init.d/apache2 restart
  7. This should do it! Wink

Leave a Reply