Hướng dẫn Block/Allow IP/dải IP truy cập vào website

Bằng cách edit file vhost của domain, bạn có thể cho phép một đại chỉ IP cố định truy cập vào website và block tất cả các địa chỉ IP còn lại.

1.Block IPs

Bạn có thể thêm IP trực tiếp vào file vhost của domain.

File Vhost sẽ có dạng: /etc/nginx/conf.d/domain.com.conf

Bạn edit tương tự:

server {
	    listen   80;
......
    	root /home/domain.com/public_html;
      deny    111.222.333.444;
      deny 91.212.45.0/24;
......
    	server_name domain.com;
......

Nếu muốn block tất cả IP:

server {
	    listen   80;
......
    	root /home/domain.com/public_html;
        deny all;
......
    	server_name domain.com;
......

Lưu lại sau đó test nginx .

nginx -t

Output như dưới là OK, bạn khởi động lại Nginx để thay đổi có hiệu lực

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Khởi động lại nginx

service nginx restart

2. Allow IPs

Cho phép duy nhất  IP  123.456.789 truy cập website, ta edit vhost  như sau

server {
	    listen   80;
......
    	root /home/domain.com/public_html;
        allow 123.456.789;
        deny all;
......
    	server_name domain.com;
......

Sau đó lưu lại, test và khởi động lại nginx.

Allow / Deny truy cập vào một thư mục, Files

Bảo vệ folder

location = /protect_folder/ {
  allow 123.456.789;  
  deny all;
}

Chặn không cho download file .zip trong các thư mục upload, files

location ~* /(?:uploads|files)/.*\.zip$ 
{
        deny all;
}

Chặn không cho run các file php  trong các thư mục upload, files

location ~* /(?:uploads|files)/.*\.php$ 
{
        deny all;
}

Bảo vệ các files Perl/cgi/…

#  Protect Perl/CGI/etc files
location ~* \.(pl|cgi|py|sh|lua)\$ 
{
        return 444;
}

Bảo vệ Git files

# Protect .git files
location ~ /\.git 
{ 
        access_log off; 
        log_not_found off; 
        deny all; 
}

Bảo vệ các file lưu trữ thông tin nhạy cảm

location ~ /(\.|wp-config.php|readme.html|license.txt|schema.txt|password.txt|passwords.txt) 
{ 
        deny all; 
}

Lưu lại, test và khởi động lại nginx.

3. Allow/Deny theo danh sách

## Block And Allow IP
 include /etc/nginx/allow-block-ip.conf;

Ta edit /etc/nginx/allow-block-ip.conf nội dung tương tự như sau:

deny 11.22.33.44;
deny 123.567.897/24;
allow 333.444.555.666;

Lưu lại, test và khởi động lại nginx.