How to block an IP address with ufw on Ubuntu Linux server

See all Ubuntu Linux related FAQ
I am using UFW to manage firewall on my Ubuntu Linux 12.04/14.04/16.04/18.04/20.04/22.04 LTS server. I need to block a specific IP address from accessing my server. Here is to block an IP address using ufw.

UFW (Uncomplicated Firewall) is a front-end for iptables command/nftables command and is particularly well-suited for a single server or host-based firewalls. It is the default firewall configuration tool for Ubuntu Linux. The UFW developed for a new sysadmin with ease use in mind. It is a user-friendly way to create an IPv4 or IPv6 based firewall to protect the server. Let us see how to block an IP address with ufw on Ubuntu server.
Tutorial details
Difficulty level Easy
Root privileges No
Requirements Linux terminal
Category Firewall
OS compatibility AlmaLinux Alpine Arch Debian Fedora Linux Mint openSUSE Pop!_OS RHEL Rocky Stream SUSE Ubuntu
Est. reading time 4 minutes

ufw block specific IP address

The syntax is:
$ sudo ufw deny from {ip-address-here} to any
To block or deny all packets from, enter:
$ sudo ufw deny from to any

Block an IP address ufw

Instead of deny rule we can reject connection from any IP as follows:
$ sudo ufw reject from to any
You use reject when you want the other end (attacker) to know the port or IP is unreachable. However, we use deny for connections to attackers (hosts) you don’t want people to see at all. In other words the reject sends a reject response to the source, while the deny (DROP) target sends nothing at all.

Show firewall status including your rules

Verify newly added rules, enter:
$ sudo ufw status numbered
$ sudo ufw status

Fig.01: ufw firewall status

Fig.01: ufw firewall status

ufw block specific IP and port number

The syntax is:
$ sudo ufw deny from {ip-address-here} to any port {port-number-here}
To block or deny spammers IP address to port 80, enter:
$ sudo ufw deny from to any port 80
Again verify with the following command:
$ sudo ufw status numbered
Sample outputs:

Status: active
	 To                         Action      From
	 --                         ------      ----
[ 1] 80/tcp        ALLOW       Anywhere
[ 2] 22/tcp        ALLOW       Anywhere
[ 3] Anywhere                   DENY
[ 4] 80                         DENY IN

ufw deny specific IP, port number, and protocol

The syntax is as following when you need to block by IP address, port number and protocol:
$ sudo ufw deny proto {tcp|udp} from {ip-address-here} to any port {port-number-here}
For example block hacker IP address to tcp port 22, enter:
$ sudo ufw deny proto tcp from to any port 22
$ sudo ufw status numbered

ufw block subnet (CIDR)

A subnetwork (also known as “subnet”) is a logical subdivision of an IP network. Subnetting is the practice of dividing a network into two or more networks. The routing prefix may be expressed in Classless Inter-Domain Routing (CIDR) notation. For example, having 24 bits allocated for the network prefix as follows:

Address:          11000000.10101000.00000001. 00000000
Netmask: = 24   11111111.11111111.11111111. 00000000
Wildcard:            00000000.00000000.00000000. 11111111
Network:       11000000.10101000.00000001. 00000000
HostMin:          11000000.10101000.00000001. 00000001
HostMax:        11000000.10101000.00000001. 11111110
Broadcast:        11000000.10101000.00000001. 11111111
Hosts/Net: 254                   Class C, Private Internet

The ufw command syntax is as follows:
$ sudo ufw deny proto tcp from sub/net to any port 22
$ sudo ufw deny proto tcp from to any port 22

How do I delete blocked IP address or unblock an IP address again?

The syntax is:
$ sudo ufw status numbered
$ sudo ufw delete NUM

To delete rule number # 4, enter:
$ sudo ufw delete 4
Sample outputs:

 deny from to any port 80
Proceed with operation (y|n)? y
Rule deleted

Tip: UFW NOT blocking an IP address

UFW (iptables) rules are applied in order of appearance, and the inspection ends immediately when there is a match. Therefore, for example, if a rule is allowing access to tcp port 22 (say using sudo ufw allow 22), and afterward another Rule is specified blocking an IP address (say using ufw deny proto tcp from to any port 22), the rule to access port 22 is applied and the later rule to block the hacker IP address is not. It is all about the order. To avoid such problem you need to edit the /etc/ufw/before.rules file and add a section to “Block an IP Address” after “# End required lines” section.
$ sudo vi /etc/ufw/before.rules
Find line that read as follows:

# End required lines

Append your rule to block spammers or hackers:

# Block spammers 
-A ufw-before-input -s -j DROP
# Block ip/net (subnet) 
-A ufw-before-input -s -j DROP

Save and close the file. Finally, reload the firewall:
$ sudo ufw reload
As noted below in the comment section, we can skip the whole process and use the following simple syntax:
$ sudo ufw insert 1 deny from {BADIPAddress-HERE}
$ sudo ufw insert 1 deny from comment 'block spammer'
$ sudo ufw insert 1 deny from comment 'Block DoS attack subnet'

You can use the comment sub-command to add comments to your UFW firewall rule. This helps in providing more context and clarity to your firewall rules. You can view added comments and rules as follows:
$ sudo ufw status verbose

Blocking multiple IP address and subnets (CIDRs) with ufw

We can use different methods to block multiple IP addresses. Let us try using bash for loop as follows to block 5 IP address:

# add subnet/CIDR too #
for i in $IPS
    sudo ufw insert 1 deny from "$i" comment "IP and subnet blocked"

Another option is to read all IP address from a text file. Create a new text file as follows using cat command:
$ cat > blocked.ip.list
Append both IPs and sub/nets:

# block list created by nixCraft

Run it as as follows using bash while loop:

while IFS= read -r block
   sudo ufw insert 1 deny from "$block" 
done < "blocked.ip.list"

See how to read file line-by-line in bash for more info.


We learned how to block an IP address or network subnet/CIDR (Classless Inter-Domain Routing) using the ufw based firewall to protect our server from bad guys.

🥺 Was this helpful? Please add a comment to show your appreciation or feedback.

nixCrat Tux Pixel Penguin
Hi! 🤠
I'm Vivek Gite, and I write about Linux, macOS, Unix, IT, programming, infosec, and open source. Subscribe to my RSS feed or email newsletter for updates.

8 comments… add one
  • P4 Jan 19, 2016 @ 21:06

    Simple indeed. I’m still a fanboy of core commands because any command wrapper could be a target of potential attacker and altering a python3 script seem to be much easier than altering a binary.

    How would you block the whole AS address space for a given AS the easiest way?

  • Gregory Feb 10, 2017 @ 19:07

    ufw insert 1 deny from {IP}
    will insert the rule at the top, so you do not need to edit the `before.rules`

  • Mikko Rantalainen May 19, 2017 @ 7:42

    You probably want to use
    ufw insert 1 reject from {IP}

    Rationale: “insert 1” is required to avoid having earlier rule allowing the connection. “reject” instead of “deny” makes it look like the port has been closed instead of looking like dropped packages.

  • Peter Sep 16, 2022 @ 0:32

    Help please.
    Where do I save the “blocked.ip.list” file if I manually create one

    • 🛡️ Vivek Gite (Author and Admin) Vivek Gite Sep 16, 2022 @ 3:02

      You can save it inside your home directory. For example, if your admin name is ‘vivek’, then /home/vivek/blocked.ip.list. That way sudo can read the file or state the full path when running while loop:

      while IFS= read -r block
         sudo ufw insert 1 deny from "$block" 
      done < "/home/vivek/blocked.ip.list"
  • Devin Miles Mar 5, 2023 @ 6:02

    Big help. Thank you friend.

  • Sophia Jul 6, 2023 @ 8:02

    Thank you for sharing your expertise and providing such valuable insights. Your post is a must-read for everyone who wish to ban IP using the “ufw command.”

  • poddmo Oct 10, 2023 @ 19:53

    Now you can install a complete blocklist solution for ufw. Search on github for ufw-blocklist
    I wrote it and have been using it for 2 years. It’s amazing how much junk traffic it blocks. The scripts can be adapted for any list of ip addresses, such as bogans or an allowlist.
    @Vivek: you may especially like the bash code to start the list reading in a subshell and then disown the job so the script returns quickly. It saves minutes off boot times when there are 1000’s of entries in the list.

Leave a Reply

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

Use HTML <pre>...</pre> for code samples. Your comment will appear only after approval by the site admin.