A fresh mix of code snippets and tutorials

Whitelist POST access with .htaccess

Here is how to whitelist POST requests for a specific file. For example, you can protect chat, forum, and other heavily targeted scripts from malicious acitivity.

Using my plugin Simple Ajax Chat as an example, the main chat script simple-ajax-chat-core.php is well-secured, but it’s possible to go further. Consider the following slice of .htaccess:

<IfModule mod_rewrite.c>
	RewriteEngine On
	RewriteCond %{REQUEST_URI} simple-ajax-chat-core.php
	RewriteCond %{HTTP_REFERER} !^https://wp-mix.com [NC,OR]
	RewriteCond %{HTTP_USER_AGENT} ^$
	RewriteRule .* - [F,L]

When added to your site’s root .htaccess file, this technique ensures that POST requests for the specified file are allowed only if coming from your site, or if using a blank/empty user agent. It’s the same technique that’s used to block no-referrer requests for WordPress.

Note that this script is for SAC version 20160408 and better. For older versions, change simple-ajax-chat-core.php to simple-ajax-chat.php.

Tip: to use this technique to protect a different file, just change the simple-ajax-chat-core.php to the name of your file. Also don’t forget to change the domain name (currently https://wp-mix.com) to match your own.

Learn more

.htaccess made easy