Apache redirect www.domain.com to domain.com

Posted on in Categories , , last updated May 12, 2008

Q. How do I remove www from all my urls so that search engine can only rank domain.com/ urls under Linux Apache web server?


A. Add following code to your .htaccess or httpd.conf (directory directive) file:

RewriteEngine On 
RewriteCond %{HTTP_HOST} ^www.yourdomain.com$ [NC]
RewriteRule ^(.*)$ http://domain.com/$1 [R=301,L]

If you added directives to httpd.conf, restart Apache:
# service httpd restart

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

5 comment

  1. Hi,
    I’m in a “extremely incompetent hosting company” situation :) that don’t permit me to use my website without DNS.
    Now I’ve put a webserver APACHE on my PC always on with static IP and I’ve forwarded the DNS * and @ to my IP to get the request without www for my website and “redraw” them with WWW.
    I have some problems in doing this.
    For now I’ve tried this:

    $server = $_SERVER[‘SERVER_NAME’]; header(‘Location: http://www.’ . $server);

    but doesen’t work with every page (i.e. http://website.ext/* for every possible string in *).
    Can you suggest me how to fix this problem?
    I repeat, I have an apache webserver so I can also modify settings in apache if is not possible to do this only with PHP.
    Thanks so much.
    PS: It can be better if this fix works independent by domain name, so I can help people with same problem.
    For knowing, the hosting company is TopHost.it
    I remember you that my website is hosted OUTSIDE my pc! SO I need only a REDIRECT

Leave a Comment