9

I'm running the CodeIgniter platform, which uses .htaccess to accept URLs like

http://www.mysite.com/controller/function/argument

I currently use some .htaccess rewrites, namely (simplified):

RewriteEngine On
RewriteCond %{REQUEST_URI} !^(/index\.php|/images|/assets)
RewriteRule ^(.*)$ /index.php/$1 [L]

I want to add a rewrite rule that redirects all non www requests to www. I also want the URI string following the domain name to stay the same in the redirect. For instance, if a user makes a request for http://mysite.com/controller/function/argument, I want the .htaccess file to rewrite the request in the browser as http://www.mysite.com/controller/function/argument and then process the request.

Steven
  • 17,796
  • 13
  • 66
  • 118

3 Answers3

14

I had a similar problem, and this .htaccess works for me

RewriteEngine On                           

#This bit rewrites your host name to include www
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,NC,L]

#This bit does the codeigniter magic
RewriteCond %{REQUEST_FILENAME} !-f  
RewriteCond %{REQUEST_FILENAME} !-d  
RewriteRule ^(.*)$ /index.php/$1 [L]
ekhaled
  • 2,930
  • 20
  • 24
10

It should be something like this:

RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
Hristo Valkanov
  • 1,689
  • 22
  • 33
rossoft
  • 2,182
  • 17
  • 17
  • This won't interfere with my second RewriteRule right? I understand your RewriteCond, I don't want to apply to the rules I already have. – Steven Nov 06 '09 at 08:14
  • If you add mine as the first one, it will only be activated if the host is not www.mysite.com. If it is activated, there will be a redirect HTTP, and the second HTTP query will activate your own rewrite if the conditions are met – rossoft Nov 06 '09 at 08:36
  • @Steven Xu, RewriteConds only apply to the next immediate RewriteRule. – Jeremy Stein Nov 06 '09 at 15:26
0

If you are on apache 2.4 ,You can use the following simple redirect :

<if "%{HTTP_HOST} =='example.com'">
Redirect / http://www.example.com/
</if>
Amit Verma
  • 40,709
  • 21
  • 93
  • 115