Ayush
Ayush

Reputation: 42450

htaccess rewrite not working as it should with www

I'm working on a CodeIgniter based application. My htacess looks like this:

RewriteEngine On
RewriteCond  %{REQUEST_FILENAME} !-f
RewriteCond  %{REQUEST_FILENAME} !-d
RewriteBase /
RewriteRule ^(.*)$ /index.php?$1 [L]
RewriteCond %{HTTP_HOST} ^www.example.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [R=301,L]

This works great for the most part, and I can access controllers and methods like this:

http://example.com/controller/method/args

However, if it is appended with a www, like this

http://www.example.com/foo

It redirects to

http://example.com/index.php?foo

The page displayed is always the index page of my site.

I added the last pair of RewriteCond / RewriteRule simply to remove www if present.

I'm not quite sure how to get it to work the way I want, so that

http://www.example.com/foo

just redirects to

http://example.com/foo

EDIT

From my CI config file:

$config['base_url'] = 'http://example.com/';
$config['index_page'] = '';
$config['uri_protocol'] = 'AUTO';

Upvotes: 0

Views: 87

Answers (2)

Pete Mitchell
Pete Mitchell

Reputation: 2879

Not really offering any more than Steven Lu here...but cleaned up your order to make a bit more sense

RewriteEngine On
RewriteBase /

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

RewriteCond  %{REQUEST_FILENAME} !-f
# You don't really need the !-d (directory) flag here
RewriteRule ^(.*)$ /index.php [L] # Could put QSA in here too, but CI doesn't play too nice with query strings 

Upvotes: 1

Steven Lu
Steven Lu

Reputation: 2180

As mentioned in the comment.

Your rewrite rule RewriteRule ^(.*)$ /index.php?$1 [L] should be placed at the bottom. Order matters in this case due to your [L] flag.

Upvotes: 3

Related Questions