By practise I do a 301 redirect non-www -> www for my production server deployments. But I have a little annoying problem/discrepency with the .htaccess rewrite settings between my development server & the production server.

If I leave the non-www -> www 301 redirect condition in the .htaccess file (which gets deployed with the website) my development webserver tries to redirect "http://localhost/mysite" to "http://www.localhost/mysite" which doesn't work.

So I have to switch between .htaccess rewrite conditions depending on the server, and this is a little cumbersome.

Is there any way of using a conditional statement to achieve something like...

# Rewrite "www.domain.com -> domain.com" 
<IfModule mod_rewrite.c>
  <If !localhost>         #This is not valid code
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
    RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
    RewriteCond %{HTTP_HOST} (.+)$ [NC]
    RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L]

Or is there a smarter way around this?

Looking forward to your ideas. Thank you very much. Prembo.

1 Answer 1


Looks like your config intends to remove a www from localhost requests, if I'm understanding that right? That part shouldn't be necessary, so let me know if I'm missing something.

How about something like this:

RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} !^localhost$ [NC]
RewriteCond %{HTTP_HOST} !^www\..*$ [NC]
RewriteCond %{HTTP_HOST} ^(.+)$ [NC]
RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L]
  • Thanks very much for your suggestion. I tried it. When I try to access the URL or IP address of LAN with a port number or directory (eg. localhost:2222/subdir or , it prepended the www, so I added the following conditions... RewriteCond %{HTTP_HOST} !^localhost.*$ [NC] RewriteCond %{HTTP_HOST} !^192.168.2\..*$ [NC] Do you forsee any side-effects from these conditions? It seems to work. Thanks again...
    – Prembo
    Commented Oct 3, 2011 at 0:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .