A fresh mix of code snippets and tutorials

Protect against SQL Injection

Here is a nice copy/paste .htaccess snippet to help block SQL-injection attacks. It can be added as-is to your .htaccess file to help protect against SQL injection and other types of malicious activity. This code is a not a replacement for proper data sanitization, but it does help to add another layer of security to your Apache-powered website.

The Code

The following set of Apache directives are derived from my work on the 6G and 7G Firewall. So if you’re using either of those, you’ve already got this technique covered (and much more). That said, here is the code:

# Protect against SQL Injection
# @ https://wp-mix.com/protect-against-sql-injection/
<IfModule mod_rewrite.c>
	RewriteCond %{QUERY_STRING} (eval\() [NC,OR]
	RewriteCond %{QUERY_STRING} (javascript:)(.*)(;) [NC,OR]
	RewriteCond %{QUERY_STRING} (base64_encode)(.*)(\() [NC,OR]
	RewriteCond %{QUERY_STRING} (GLOBALS|REQUEST)(=|\[|%) [NC,OR]
	RewriteCond %{QUERY_STRING} (<|%3C)(.*)script(.*)(>|%3) [NC,OR]
	RewriteCond %{QUERY_STRING} (\\|\.\.\.|\.\./|~|`|<|>|\|) [NC,OR]
	RewriteCond %{QUERY_STRING} mosConfig_[a-zA-Z_]{1,22}(=|%3D) [NC,OR]
	RewriteCond %{QUERY_STRING} (boot\.ini|etc/passwd|self/environ) [NC,OR]
	RewriteCond %{QUERY_STRING} (\'|\")(.*)(drop|exec|insert|md5|select|union) [NC]
	RewriteRule .* - [F]

No modifications are required, it’s all plug-n-play. But remember to test well after adding to your site before going live. Also note that techniques like this won’t 100% guarantee anything but it does help stop a ton of the most common types of SQL-injection attacks. For more information about how this works and other ways to secure via Apache/.htaccess, check out the nG-series Firewall at Perishable Press.

Learn more

.htaccess made easy