Menu

Redirect to www or non-www in Htaccess

For SEO purposes this is good practice to keep your website urls either with www or without www only. In this tutorial you will learn how to force redirect to www or non-www url only. 301 status code tells search engines that the page has permanently moved to a new location.
Force Redirect to WWW or Non-WWW
Login to server with admin privileges and navigate to document root of your website. Now create a .htaccess file using one of below content as per your requirements.

Force non-www to www

This will force url as www.example.com, this will always add www in url either you accessed it with or witout www.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301,NC]

Force www to non-www

This will force url as example.com, this will always remove www from url, you either accessed it with or witout www.
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301,NC]

Enable .htaccess to Work

Before using .htaccess, make sure your .htaccess is enabled to use in Apache. To enable this add following settings under your domains VirtualHost.
<VirtualHost *:80>

    [...]
    <Directory "/home/user/public_html">
         Allowoverride all
    </Directory>
    [...]

</VirtualHost>

Enable Apache Rewrite Module

Also make sure Apache rewrite module is enabled. If not use the following command to enable module.
$ sudo a2enmode rewrite
Hack The Security
Hack The Security Twitter
Hack The Security Facebook

About Author:


I am a Linux Administrator and Security Expert with this site i can help lot's of people about linux knowladge and as per security expert i also intersted about hacking related news.TwitterFacebook

Next
Newer Post
Previous
Older Post

0 comments:

Post a Comment

 
Top