Requirements: Use nginx to block some IPs from accessing websites, such as crawlers, ads, etc. Or for policy reasons, you need to block access from an IP address in a certain country.
Block specified IP access
Nginx provides two of the most basic commands for masking and allowing IPs: deny to block and allow to allow, as follows:
Specify directory to block access from specified IPs
In Nginx's configuration file, you can use location blocks to match specific URL paths. For example, we want to enable masking in URL paths that start with /foo, matching all URL paths that start with /foo, such as /foo/bar and /foo/baz/qux, etc., as follows:
If you wantExact match /footo use the following configuration:
You can also match the directory with regex:
Block access to the specified country (region).
Sometimes we want to allow only certain regions to access our website. Knowing the above two methods, the remaining problem is how to get all the IP segments in a certain region. We can get it from ip2location. Address:The hyperlink login is visible.
Select the country on the left side of the box, select V4 or V6 in the middle box, and select the rule type on the right. Take Japan as an example:
Download and unzip to get the txt file,Delete the first location / { and the last },Finally, add a line allow all;Change the suffix name from .txt to .conf and upload it to the server, remembering the directory where it was placed. (e.g. /usr/local/nginx/conf/nginx.conf/firewall.conf)
Modify the Nginx configuration file corresponding to the site, such as /foo directory to only allow access from non-Japanese IPs:
If you want it to be site-wide, you can write to the sever or http field, for example:
Then enter the following command to reload the nginx configuration:
|