5. november 2010

Search Engine Friendly URLs with .htaccess and mod_rewrite

Search Engine Friendly URLs with .htaccess and mod_rewrite:

I was recently developing a PHP website that used mod_rewrite to make its URLs search engine friendly. Websites have been using mod_rewrite and .htaccess strategies to do this for years now and there are a 100 ways to accomplish the task. One issue that was occurring with this site was URLs without the a trailing slash would work, but URLs with a trailing slash would break (trigger a 404 error):

//works

http://mydomain.com/my-page

//breaks

http://mydomain.com/my-page/

The original .htaccess source was:

#adds '.php' to a URL that isn't a directory or a file
RewriteCond %{REQUEST_URI} !(\.[^./]+)$
RewriteCond %{REQUEST_fileNAME} !-d
RewriteCond %{REQUEST_fileNAME} !-f
RewriteRule (.*) $1.php [L]

The solution was simple: an extra statement to accommodate for the trailing slash:

#removes trailing slash if not a directory
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [R=301,L]

#adds '.php' to a URL that isn't a directory or a file
RewriteCond %{REQUEST_URI} !(\.[^./]+)$
RewriteCond %{REQUEST_fileNAME} !-d
RewriteCond %{REQUEST_fileNAME} !-f
RewriteRule (.*) $1.php [L]

This method may be a bit inefficient as there are two redirects but it does the job. Do you have a better solution? If so, share it!