Apache mod_rewrite: force www only if not in localhost

StackOverflowNewbie picture StackOverflowNewbie · Apr 19, 2012 · Viewed 23.3k times · Source

I have the following in my htaccess to force the www in URLs:

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

How do I only apply this if not on localhost? Is there some sort of if-condition I can put? Right now, I'm getting something like this: http://www.localhost/ ...

Answer

LazyOne picture LazyOne · Apr 19, 2012

RewriteCond is already your "if-condition". Just add another one:

RewriteCond %{HTTP_HOST} !=localhost
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]