Question

How to block country to access website using NGINX in CentOS 8?

Hi there,

I am really new to this. I will appreciate if anyone can help on how to block country level access via NGINX.

Thanks Hetal


Submit an answer
Answer a question...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

alexdo
Site Moderator
Site Moderator badge
April 23, 2022

Hello there,

You can use Nginx’s http_geoip_module to restrict access from a specific geo-location or country to your website. You can check the following article:

https://fedingo.com/how-to-block-ip-by-country-in-nginx/

Another thing is using iptables to block the traffic before reaching Nginx at all. I found this guide that should be helpful. This references blocking Chinese IPs and the script near the bottom uses a third-party service to source the IP lists.

https://mattwilcox.net/web-development/unexpected-ddos-blocking-china-with-ipset-and-iptables/

Hope that this helps!

KFSys
Site Moderator
Site Moderator badge
April 22, 2022

Hi @hetalpatel,

I’m not sure Nginx is the right place for this block. This is more of a firewall thing. As such, I’ll suggest adding the country block level on your firewall.

I’ve used CSF for such measures and I can confirm it works properly. In order to block a country you can use the CC_DENY option which accept two-letter country codes such as US, GB and etc.

In order to list more than one country you just need to separate them using comas:

CC_DENY = "AB,CD,EF"

You may find a list of ISO 3166-1 alpha-2 codes at https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2

If you’re not familiar with CSF or you want to install it on CentOS or Ubuntu droplet check out this mini tutorial:

For CentOS:

https://www.digitalocean.com/community/questions/how-to-install-and-configure-config-server-firewall-csf-on-centos

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.