Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

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]
  <else>
    RewriteCond %{HTTPS} !=on
    RewriteCond %{HTTP_HOST} !^www\..+$ [NC]
    RewriteCond %{HTTP_HOST} (.+)$ [NC]
    RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L]
  </If>
</IfModule>

Or is there a smarter way around this?

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

share|improve this question

1 Answer 1

up vote 2 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 192.168.100.10:2222/subdir) , 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

 
discard

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.