WP-Mix

A fresh mix of code snippets and tutorials

Redirect Attacker to Special Message

If you are using Apache server, you can stop an attack by getting the IP address of the attacker and then using it to block or redirect all of their requests. Normally I just block the requests using either Deny or Require directives (depending on Apache version), but sometimes it’s fun to redirect the attacker to a special page. Where they can read something relevant to the current situation. Or view a nice photo or animated GIF. Use your imagination here.

Say Goodbye

Here is the magic code that you can drop in to your .htaccess file:

# Redirect IP to special message
<IfModule mod_rewrite.c>
	RewriteCond %{REMOTE_ADDR} ^123\.123\.123\.123$
	RewriteRule (.*) /special-message.php [R=301,L]
</IfModule>

The IP address is specified in the RewriteCond, with each dot escaped so that is is not a wildcard (no false positives). The ^ denotes the beginning of the address, and the $ denotes the end of of the address. Again, these are to prevent false positives. You only want to target the attacker.

The RewriteRule is where the action happens. There we match any request via wildcard, and then redirect to the relative URL, which in this case is /special-message.php. Then lastly the rewrite flags are added — R=301 and L. The R defines the HTTP response, and the L instructs Apache to stop the rewriting process and not apply any more rules.

Usage

To use the above code, add it to your site’s root, web-accessible .htaccess file. On many hosts this would be located in a directory named something like public_html. Then get the IP address of the attacker. Usually this can be found in your site access and/or error/debug logs. Lastly, make the following changes to the code:

  • Replace the IP address with the one you want to target
  • Replace the relative path in the rewrite rule with the location of the file that contains something special for your unwanted visitor

Then save changes, upload to server, and test well. You can use free proxy services to help with testing different IP addresses.

Or, if you would rather just block the attacker based on their IP address, you can replace the RewriteRule line with this:

RewriteRule (.*) - [L]

That will serve each request from the specified IP with a 403 – Forbidden response.

Learn more

.htaccess made easy