My standard htaccess rewrite rules for ExpressionEngine

Posted in Web Design on Tuesday, 28th May 2013 at 8:55AM

My standard htaccess rewrite rules for ExpressionEngine

Over the years that I have been using ExpressionEngine my htaccess file has evolved to meet various requirements and I am sure it will continue to do so.  The current iteration is based largely on the one supplied with HTML5 Boiler Plate but I have adapted the re-write section to do a few different things that I find useful.

With certain sites I have need to ensure that the URLs are always the same (ie. no www/non-www option).  This is also considered good practice for SEO purposes to avoid duplicate URL's so is a good idea regardless.

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

It is fairly common to remove the index.php URL segment but on some sites I was finding for one reason or another it was creeping back in, especially on the homepage.  I also felt that to avoid the duplicate URL issue it was worth ensuring requests to index.php where always redirected to their 'clean' counterpart.  This snippet completely removes index.php even if it has been entered in the address bar (taken from this forum post).

# Remove index.php from URL's and redirect
RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,L]

And finally I use ExpressionEngine's recommended rules to allow for the index.php removal.

# Recommended ExpressionEngine index.php removal
RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]

And here it is in it's entirety.  I will update it as it evolves.

<IfModule mod_rewrite.c>

Options +FollowSymlinks
RewriteEngine On
  
# Ensure www is always present
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]
 
# Remove index.php from URL's and redirect
 RewriteCond %{THE_REQUEST} ^GET.*index\.php [NC]
 RewriteCond %{THE_REQUEST} !/system/.*
 RewriteRule (.*?)index\.php/*(.*) /$1$2 [R=301,L]

# Recommended ExpressionEngine index.php removal
RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]

</IfModule>

Add your comment

Remember me?

Notify me of follow-up comments?

Michael's Paintings

The Path to LiuGong

The Path to LiuGong
39.5 x 39.5 cm
Acrylics and Indian ink on canvas

Michael's photos

Cornet Fish

Cornet Fish
Red Sea, Egypt

Featured Web Project

Carver Harvey - Home page

Project: Carver Harvey
URL: http://www.carverharvey.co.uk