I'm using the following code in my .htaccess in order to redirect to the www version of the website and also to add a trailing slash by default. It all seems to work, but I wondered is this the most efficient way of doing it. I'm no expert on this side of things, so I've bolted this lot together from the official EE docs and a couple of separate articles I found on the subject.

RewriteEngine On

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

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+[^/])$ /$1/ [R=301,L]

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

AddHandler php5-script .php

Should I (if possible) combine the rules? At the minute you can end up with two 301 redirects if you go to the non www version of the website without the trailing slash.

My motivation for making these changes is to improve the general SEO of the site, so any tips are most welcome.


Here's a gist I've made that you can comment/uncomment out the bits you need. To date I haven't found the need to combine rules and I haven't found many examples that actually do combine rules. I'd love to see them if find some though.

Lastly, I normally move the AddHandler stuff up in the .htaccess and keep the rewrite stuff below it.

  • Thanks Paulo. It's good to know I'm headed in the right direction. Jul 24 '13 at 9:01
  • You're most welcome! Jul 24 '13 at 17:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.