WP-Mix

A fresh mix of code snippets and tutorials

Protect Against File Injection

Here is a nice copy/paste .htaccess snippet to help block file-injection attacks. It can be added as-is to your .htaccess file to help protect against file 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 File Injection
# @ https://wp-mix.com/protect-against-file-injection/
<IfModule mod_rewrite.c>
	RewriteCond %{REQUEST_METHOD} GET [NC]
	RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=https?:// [NC,OR]
	RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=(\.\.//?)+ [NC,OR]
	RewriteCond %{QUERY_STRING} [a-zA-Z0-9_]=/([a-z0-9_.]//?)+ [NC]
	RewriteRule .* - [F]
</IfModule>

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 file-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