Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache mod_rewrite: force www only if not in localhost

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

like image 293
StackOverflowNewbie Avatar asked Apr 19 '12 15:04

StackOverflowNewbie


3 Answers

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]
like image 52
LazyOne Avatar answered Nov 04 '22 16:11

LazyOne


I added all these:

RewriteCond %{HTTP_HOST} !=localhost
RewriteCond %{HTTP_HOST} !=127.0.0.1
RewriteCond %{REMOTE_ADDR} !=127.0.0.1
RewriteCond %{REMOTE_ADDR} !=::1
like image 43
Kiran Madipally Avatar answered Nov 04 '22 16:11

Kiran Madipally


If you're using a port other than 80 (e.g. localhost:8080) you might need to add it to the regex too:

RewriteCond %{HTTP_HOST} !^localhost(?::\d+)?$ [NC]
RewriteCond %{HTTP_HOST} !^127\.0\.0\.1(?::\d+)?$
like image 5
Gus Avatar answered Nov 04 '22 17:11

Gus