Sunday, April 3, 2011

Redirect non-www URL to www URL in conjunction with other rules

Redirecting a visitor who hits http://example.com to http://www.example.com isn't terribly difficult. But how is it done in conjunction with a RewriteRule that directs all page requests through "index.php"?

RewriteRule !\.(gif|jpg|png|css|js|php|ico|xml)$ /index.php
From stackoverflow
  • You just need to make sure that those rule, that cause an external redirect, appear before those, that cause internal rewrites. So simply:

    RewriteCond %{HTTP_HOST} !^www\.
    RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    RewriteRule !\.(gif|jpg|png|css|js|php|ico|xml)$ /index.php
    
  • See the answer for this post, just do the opposite.

    <VirtualHost *:80>
        ServerName example.com/
        RedirectPermanent / http://www.example.com/
    </VirtualHost>
    
    SpoonMeiser : I was just writing something similar. I like this way because the re-directing from non-www doesn't interfere with your 'proper' virtual host at all.

0 comments:

Post a Comment