How to: Deny comment posting to no referrer requests

December 2, 2008 at 8:24 am

If you’re a WordPress user, then you’re probably upset with the amount of daily spam comments. Sure, there’s akismet, but here’s a little .htaccess trick to prevent spammers posting on your blog.

To achieve this recipe, simple paste the following code on your .htaccess file, located at the root of your WordPress install. Don’t forget to specify your blog url on line 4.
Remember to ALWAYS create a backup when editing the .htaccess file.

RewriteEngine On
RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
RewriteCond %{HTTP_REFERER} !.** [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]

The above code looks for the referer (The url from where the page has been called) when the wp-comments-post.php file is accessed. If a referer exists, and if it is your blog url, the comment is allowed. Otherwise, the sapm bot is redirected and the comment will not be posted.