Htaccess: How to redirect URL from www to non-www?

Posted by Damodar Bashyal on February 28, 2012

 

This is the universal code for redirection. First of all lets redirect from www to non-www with our .htaccess file.

#Use this for non-ssl URL redirection
<IfModule mod_rewrite.c>
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
</IfModule>

#use this for SSL enabled URLs
<IfModule mod_rewrite.c>
    RewriteCond %{HTTPS} on
    RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
</IfModule>

Similarly we can redirect from non-www to www. So, use the one you prefer. Above one or below.

#Use this for non-ssl URL redirection
<IfModule mod_rewrite.c>
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L]
</IfModule>
#use this for SSL enabled URLs
<IfModule mod_rewrite.c>
    RewriteCond %{HTTPS} on
    RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
    RewriteRule ^(.*)$ https://www.%1/$1 [R=301,L]
</IfModule>

So, Which one do you prefer?

Delight Designs posted on - Thursday 14th of March 2013 10:27:56 PM

Hello..
Is there a limit for 301 redirection in htaccess file? I have a website with 400 static html pages (my html file names are not good) and I would like to rename my html file names according to the keywords
Can I use a single .htaccess file ?
Thank you
 
not published on website


QR Code: Htaccess: How to redirect URL from www to non-www?