How to block a specific IP Address using UFW

The key to blocking a specific IP address with UFW is to make sure that the rule which blocks the ipaddress is applied before any allow rules. Because the firewalls rules are run in order – the block will no come into affect if it appears at the bottom. For example on most webserver you might expect the rules to be:

To                         Action      From
--                         ------      ----
22                         ALLOW       Anywhere
80                         ALLOW       Anywhere
443                        ALLOW       Anywhere
22                         ALLOW       Anywhere (v6)
80                         ALLOW       Anywhere (v6)
443                        ALLOW       Anywhere (v6)

Therefore, to block an IP address the rules would need to setup like this:

To                         Action      From
--                         ------      ----
Anywhere                   DENY        <ip address >
22                         ALLOW       Anywhere
80                         ALLOW       Anywhere
443                        ALLOW       Anywhere
22                         ALLOW       Anywhere (v6)
80                         ALLOW       Anywhere (v6)
443                        ALLOW       Anywhere (v6)

To do this you need to insert the new deny rule at the top using the “insert” option.

sudo ufw insert 1 deny from <ip address>

To remove the block simple:

sudo ufw delete allow from <ip address>

For more information read the community documentation for UFW on Ubuntu.

3 thoughts on “How to block a specific IP Address using UFW

  1. I’ve followed these instructions, but UFW is not blocking requests from the IP address. Any suggestions? (Trying to block the YandexBot)

    To Action From
    — —— —-
    Anywhere DENY 37.140.141.37
    Anywhere DENY 5.255.253.118
    22 ALLOW Anywhere
    80/tcp ALLOW Anywhere
    25/tcp ALLOW Anywhere
    587/tcp ALLOW Anywhere
    22 (v6) ALLOW Anywhere (v6)
    80/tcp (v6) ALLOW Anywhere (v6)
    25/tcp (v6) ALLOW Anywhere (v6)
    587/tcp (v6) ALLOW Anywhere (v6)

    1. i had same issue as coolfactor last month. i figured out my problem was iptables. iptables one rule accept port 80 was before ufw rule. so when i removed iptables port 80 rule. my problem has solved.(sorry about my poor english)

Leave a Reply