Two methods of access control for nginx

  • 2020-05-12 07:04:32
  • OfStack

The environment

System environment: CentOS 6.7

nginx version: nginx/1.8.1

1. Based on Basic Auth certification

Nginx provides the Basic Auth function of HTTP. After configuring Basic Auth, you need to enter the correct user name and password to access the website properly.

We use htpasswd to generate the password information, starting with the installation of httpd-tools, which includes the htpasswd command in httpd-tools.


yum install -y httpd-tools

Next, we can create a user and password, such as creating a user of loya, and execute the command:


htpasswd -c /opt/nginx/.htpasswd loya

According to the prompt for password twice and then create a success, then modify Nginx configuration, edit/opt/nginx/conf/vhosts/www conf, behind the configuration to add two lines of configuration:


server {
  ....
  auth_basic "Restricted";
  auth_basic_user_file /opt/nginx/.htpasswd;
}

reload nginx in effect


/opt/nginx/sbin/nginx -s reload

2. Access control based on IP

Access control via IP based on the nginx module ngx_http_access_module,

1. Module installation

ngx_http_access_module is built into nginx, unless the compilation installation specifies the wok without-http_access_module, which of course no one does.

2. Instruction

allow

Grammar: allow address | CIDR | unix: | all;

Default value: -

Configuration section: http, server, location, limit_except

Allow access to an ip or 1 ip segment. If you specify unix:, this will allow access to socket, which was added in 1.5.1.

deny

Grammar: deny address | CIDR | unix;

Default value: -

Configuration section: http, server, location, limit_except

Access to an ip or 1 ip segment is disabled. If you specify unix:, access to socket will be disabled. unix is new in 1.5.1.

Example 3.


location / {
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
allow 2001:0db8::/32;
deny all;
}

The order from top to bottom is similar to iptables. The match pops up when it arrives. The above example first banned 192.16.1.1, then allowed 3 network segments, including 1 ipv6, and finally banned all unmatched IP.

Those that are deny will return a 403 status code.

conclusion


Related articles: