The Nginx user authentication configuration method details the of domain name and directory
- 2020-05-06 12:16:37
- OfStack
Nginx can add user authentication to a domain name separately, as follows:
Generate username and password for user authentication:
#wget -c soft.vpser.net/lnmp/ext/htpasswd.sh;bash htpasswd.sh
Enter
as prompted
User name:
Password:
File name:
The script automatically generates the authentication file, auth.conf, which reads:
/usr/local/nginx/conf/auth.conf
2. Add auth authentication configuration
for NginxTake the auth directory under a domain name as an example. Add the following code to the server section of the domain name:
location ^~ /auth/ {
location ~ .*.(php|php5)?$ {
fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_index index.php;
include fcgi.conf;
}
auth_basic "Authorized users only";
auth_basic_user_file /usr/local/nginx/conf/auth.conf
}
auth_basic_user_file is the
path for the htpasswd file3. Restart Nginx
Access to http://yourdomainname/auth/ prompts for a username and password.
If we only want to add user authentication for the directory the above method is not shown, let me introduce the specific directory user authentication
Add user authentication (auth basic)
to the directorynginx's auth_basic authentication USES a password file that is compatible with apache, so we need to generate the password file through htpasswd of apache.
First look for htpasswd
on your system
find / � name htpasswd
Generally, CentOS will be equipped with apache, which is located at:
/usr/bin/htpasswd
If not, install
yourself
yum install apache
And find the htpasswd file address.
Once we find the htpasswd file, we create a user, such as es150 en 151en
/usr/bin/htpasswd � c /usr/local/ngnix/conf/authdb xiaoquan
The above command creates the authdb password file for xiaoquan in the nginx profile directory, but you can also create the authdb password file elsewhere, where nginx profile is easier to use.
Enter the above command and you will be prompted to enter the password prompt message, enter twice, you can add success.
Next, modify the nginx configuration file to add
under an server configuration that requires auth_basic
location /admin/ {
auth_basic "QuanLei Auth.";
auth_basic_user_file /usr/local/ngnix/conf/authdb;
}
finally lets nginx use the latest configuration:
/usr/local/ngnix/sbin/nginx -s reload
Also, if you are using a clustered environment, Proxy_Pass:
location /admin/ {
proxy_pass http://cluster/mgmt/;
auth_basic "QuanLei Auth.";
auth_basic_user_file /usr/local/ngnix/conf/authdb;
}