Using .htaccess to Block Comments

Allowing “just anybody” to write comments on your site comes with a potential cost: quite often these comment writers are spam. They’re only writing comments in the hopes of getting a valuable backlink from your site to their own and boost their SEO rankings.

So if you want to reduce the “spam” and allow only real people to post comments, here’s a handy method that can help with that. Modify your .htaccess file, adding the following at the bottom:

# guard against spammers
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
  RewriteCond %{HTTP_REFERER} !* [OR]
  RewriteCond %{HTTP_USER_AGENT} ^$
  RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]

On line 6, you’ll need to change to be your own domain name.

This works by checking the REQUEST_URI – that’s the URL that is being requested, for wp-comments-post.php. When this script is being run, comments are being added to your blog. When a request comes in for wp-comments-post.php, it also checks the HTTP_REFERRER to be your web site. If it is your web site, then a request to post a comment came from your web site and was sent to wp-comments-post.php — this is the normal expected behavior. If the referrer is not your web site or if it doesn’t specify a User Agent, then it’s very likely that the request to post a comment is coming from a spam bot, so it refers the post back to the sender’s IP address.

This way, only valid comment posts that are coming from your domain are allowed through to the wp-comments-post.php script and will add the comments to your database. Anything else gets sent back to where it came from.

Don’t think of this as a cure-all. It’s not. It’s just one more tool in your arsenal that can help reduce the spam that your web site is being inundated with. But adding this and other spam prevention tools gives you a multi-tiered solution and helps to combat the problem.

Leave a Comment

Your email address will not be published. Required fields are marked *