Redirect non-www domain but not IP's
I am looking for a way to rewrite non-www-domains to www-domains, while at the same time not redirecting direct IP-requests.
I have multiple sites on the same server - that is: a default (virtual)host and one VirtualHost with a ServerName and multiple ServerAlias'es, which work perfectly. I prefer the domainnames to start with "www". So I have hacked the following code together, which works great:
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
It doesn't handle https, b开发者_运维问答ut the biggest problem is that requests to the server-IP are also rewritten from eg. "123.45.67.8" to "www.123.45.67.8". I could add the line below to solve that:
RewriteCond %{HTTP_HOST} !^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$
... but it is it effective? And what about IPv6?
Being no mod_rewrite-wiz, I have been trying to figure out how other people have solved this problem, but with no luck.
That's because your condition is only checking if it starts with www, try this instead (I left the optional https code):
RewriteCond %{HTTP_HOST} ^(yourdomain|thisdomain|thatdomain)\.com
#RewriteCond %{HTTPS} =on
#RewriteRule .* https://www.%{SERVER_NAME}%{REQUEST_URI} [R,L]
RewriteRule .* http://www.%{SERVER_NAME}%{REQUEST_URI} [R,L]
精彩评论