Hints and tips on mod_rewrite

These are some helpful hints on various topics.

 

Adding www to domain name

If you want you users and search bots to be redirected from http://domain.com/some-page.html to http://www.domain.com/some-page.html for any page some-page.html add the following code to you .htaccess file.

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\.domain\.com$
RewriteRule .* http://www.domain.com%{REQUEST_URI} [L,R=301]

Erorr "400 Bad request" when using mod_rewrite

Sometimes when you use mod_rewrite you get "400 Bad request" error, when accessing directory  without  trailing slash. For example http://domain.com/forum returns "400 Bad request" when forum is directory while http://domain.com/forum/ has normal response. To fix this issue use this fragment in your .htaccess file:

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