Search code examples
.htaccessno-www

redirect non-www to www resulting in loop address


I'm configuring my website to redirect any non-www to www, but resulting in address loop like this:

abc.com/www.abc.com/index.php/www.abc.com/index.php/www.abc.com/index.php/www.abc.com/index.php/www.abc.com/index.php ... and so on

Below is my .htaccess file. Can anyone help me to spot my error?

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ /index.php?/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^(/index\.php|/assets|/robots\.txt|/favicon\.ico)
RewriteRule ^(.*)\.html$ /index.php/$1 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !^(/index\.php|/assets|/robots\.txt|/favicon\.ico)
RewriteRule ^(.*)$ /index.php/$1 [L]

RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ www.%{HTTP_HOST}/index.php/$1 [R=301,L]
</IfModule>

<IfModule !mod_rewrite.c>
ErrorDocument 404 /index.php
</IfModule>

Many Thanks,


Solution

  • RewriteRule ^(.*)$ www.%{HTTP_HOST}/index.php/$1 [R=301,L]
                       ^---
    

    You forgot to prefix the hostname with http://, so Apache's rewriting as a LOCAL url

    Try

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

    instead.

    It's basically the same rules that apply to:

    <img src="www.example.com/kittens.jpg" />
    <img src="http://www.example.com/kittens.jpg" />