Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 " ->" 
<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.

share|improve this question
up vote 3 down vote accepted

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]
share|improve this answer
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 Oct 3 '11 at 0:55

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.