views:

227

answers:

3

Hi guys,

There is a problem with my .htaccess file. If I type in "website.com" it redirects me correctly to "www.website.com", but if I type in "website.com/level1/level2" it redirects me to "www.website.com/index.php/level2" and gives me a 404 error.

Here is what I have in my .htacces file:

Options +FollowSymLinks
IndexIgnore */*

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . index.php

AddDefaultCharset UTF-8

#Redirect from website.com to www.website.com
RewriteCond %{HTTP_HOST} ^website\.com$ [NC]
RewriteRule ^(.*)$ http://www.website.com/$1 [L,R=301]

Any suggestion how to solve the issue?

Thank you.

A: 

I think what's happening is that you are rewriting to index.php before you are doing the external redirect. If you switch the order of your RewriteRules, it should fix the problem. Try this:

RewriteEngine on

#Redirect from website.com to www.website.com
RewriteCond %{HTTP_HOST} ^website\.com$ [NC]
RewriteRule ^(.*)$ http://website.com/$1 [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . index.php

AddDefaultCharset UTF-8

This way, the external redirect to www is done first, and when the request comes back, the internal index.php is then applied, instead of the other way around.

zombat
A: 

If you have access to the server config, it is better to do hostname redirects with plain old Redirect which is designed for this exact situation. Don't resort to the complexity of mod_rewrite until you really need to.

Remove the ServerAlias for example.com in the <VirtualHost> for your main web site, and add it as a separate virtualhost instead:

<VirtualHost *:80>
    ServerName example.com
    Redirect permanent / http://www.example.com/
</VirtualHost>
bobince
A: 

Always put rules that cause an external redirect before those rules that just cause an internal redirect. Otherwise an already internally rewritten URL would be redirected externally using the internal URL.

So in your case swap the order of your two rules putting the rule with the R flag before the other rule:

RewriteCond %{HTTP_HOST} ^example\.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php
Gumbo