How do I protect joomla site using .htaccess and mod_rewrite?

By | 2 October 2007

Someone has created a set of mod_rewrite conditions (below) that you can tag onto the end of your .htaccess file. These conditions will block a good number of common exploit attempts while interferring as little as possible with legitimate usage.

Each server configuration is unique. If you are forwarded to your home page and receive a 403 Forbidden error, you will know these settings worked incorrectly on your site. If a particular rule breaks some feature of your site, just comment it out by placing a # in front of the offending rule.

Note: As of Joomla! version 1.0.11, these settings are included in the file, htaccess.txt (no dot in filename) which is automatically added to your site during the Joomla! install.

1. Append the following code to the .htaccess file in the same directory as your Joomla! index.php file (often your public_html directory).
2. Test your site.
3. If the site produces errors, comment out all of these lines, and uncomment and test one line at a time until you find the problem directive(s).
4. Try to tweak these directives to work on your server, or leave them commented out.

########## Begin – Rewrite rules to block out some common exploits
# Block out any script trying to set a mosConfig value through the URL
RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,21}(=|\%3D) [OR]
# Block out any script trying to base64_encode crap to send via URL
RewriteCond %{QUERY_STRING} base64_encode.*\(.*\) [OR]
# Block out any script that includes a tag in URL
RewriteCond %{QUERY_STRING} (\<|%3C).*script.*(\>|%3E) [NC,OR]
# Block out any script trying to set a PHP GLOBALS variable via URL
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
# Block out any script trying to modify a _REQUEST variable via URL
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
# Send all blocked request to homepage with 403 Forbidden error!
RewriteRule ^(.*)$ index.php [F,L]
########## End – Rewrite rules to block out some common exploits