How do I stop spam attack on my website?

February 22, 2016 1.7k views
Ruby on Rails Nginx DNS

Within few hours of launching my website ( on a droplet, my Nginx access log is filled with access requests like this:

* - - [22/Feb/2016:11:22:13 -0500] "GET HTTP/1.0" 404 1564 "-" "-"

First question is: how the domain "" is mapping to my public IP address?
When I ping "", it gives an IP address that is registered in China. It appears
that many others on the internet are getting spammed by these kind of attack.

Second question is: How can I stop these requests at the firewall, before it hits my application server (Rails). It seems harmless as all these requests are returned with a "404 Not found" error code. Still it is filling up my log files and creating unnecessary traffic.

Anyone else is seeing this problem?

Thanks for your help in advance.

2 Answers
Nginx is a very secure and reliable web server even with a default setup. However, there are many ways to secure Nginx further. In this article, we will use open source software exclusively while trying to follow some popular web server hardening approaches and security standards. Namely, we'll be talking about preventing information disclosure, enforcing encryption, performing audits, and limiting access.

This is where iptables and a little cron job can be useful.

If you're regularly being hit by the same IP addresses, to block them out make a rule using iptables. With spam, it's best to simply drop the traffic so try :

iptables -I INPUT -s xx.xx.xx.xx -j DROP

This will block IP address xx.xx.xx.xx accessing your droplet. You can also use CIDR format to block a range of IP Addresses if necessary.

This is not, however, persistent across a reboot so I'd recommend making a little script and run it at boot time as a cron job.

Assuming you're logged in as root (if not then su as required)

  1. Create a file called in /root/ :

    nano ~/ 
  2. On each line place a rule using iptables. Don't forget to add the path to iptables!

    /sbin/iptables -I INPUT -s xx.xx.xx.xx -j DROP
    /sbin/iptables -I INPUT -s yy.yy.yy.yy -j DROP
  3. Save the file and make it executable :

    chmod 700 ~/
  4. Test your script by running it :

  5. If all is good, set it as a cron job on reboot :

    crontab -e

Then add the following to the crontab that opens :

@reboot    /root/

This will then load and run your script as root each time you restart your server. To add new addresses to block, just add a new line to your script.

This is a basic way of dealing with spam. If you are comfortable with linux it's definitely worth looking at something like fail2ban which is a much nicer automated way of snipping spam attacks in the bud :)

I hope that helps!


Have another answer? Share your knowledge.