Conditional 301 redirect depending on server (localhost vs production)

.htaccess301-redirectapache-2.2

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.

Best Answer

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]