Ubuntu – How to Block Visitors by Country with ‘ufw’


You want to allow/deny incoming SSH connections to your server, based on originating country. Blocking needs to be done at the host OS.


You can configure ‘ufw’ to deny connections based on source IP subnets. You can get IP subnets for a specific country from IP2location.com.


  1. Go to https://www.ip2location.com/free/visitor-blocker.
  2. Near the end of the page, under “Download List”, choose “Country”, and “Output Format” as “CIDR”, and save the file.
  3. Copy the file to your Linux host. Let’s say to your home directory. And the file name is cidr-singapore.txt.
  4. Run the following bash command from your host’s home directory, to add the rules (modify the port number as needed):
cat cidr-singapore.txt | grep -v ^# | while read subnet; do sudo ufw allow proto tcp from $subnet to any port 22; done
  1. Check the status of your ufw rules again.
sudo ufw status