Question

Note: I have seen other questions/answers for redirecting www->non-www. This is more to know WHY this isn't working

So I have a VirtualHost file that looks roughly like this

<VirtualHost *:80>
    ServerName domain.com
    ServerAlias www.domain.com
    ...
    RewriteEngine on
    RewriteCond %{HTTP_HOST} www.(.+) [NC]
    RewriteRule ^/(.*) http://%{SERVER_NAME}/$1 [R=301]
    ...
</VirtualHost>

But when I try it I keep getting a redirect loop. I don't see anything telling me what it's redirecting to in the access logs.

I suspect it keeps erroneously going to www.domain.com instead of to domain.com, even though I'm sure this should be correct...

Was it helpful?

Solution

Try this rule:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

You're probably getting into loop due to use of %{SERVER_NAME} variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top