How to make nginx website require password to access ?
Make authentication file#
For example, I make the file in path /etc/nginx/htpasswd/
, and name it my_auth
.
Edit it, fill in the username you want to use to login (e.g. my_user
), followed by the :
symbol. (p.s. Dont break the new line)
Then save the file, type the following command to generate the password (change to your own path):
1openssl passwd -apr1 >> /etc/nginx/htpasswd/my_auth
Check the file, you should see the content looks like this:
1my_user:$apr1$l3IuPvhA$/KzcRqpMNC7dUBG9XwQ370
For setting mutiple users:
1my_user:$apr1$l3IuPvhA$/KzcRqpMNC7dUBG9XwQ370
2my_user2:$apr1$UePZ9SIn$HVpEhDfM5dgk2fgbGE81T/
3my_user3:$apr1$4t8dv/wc$9Gy5Hb5hnaLO5Zwey1WbJ1
Configure nginx#
Edit config file of nginx.
For example, my config file is /etc/nginx/conf.d/default.conf
, and I want to make the users require password when accessing path of website under /admin/
, add the following settings in file (server block):
1location ~ /admin/ {
2 auth_basic "Login to access files.";
3 auth_basic_user_file /etc/nginx/htpasswd/my_auth;
4}
p.s. Dont forget to change above content to your own path of auth file.
Make nginx reload the config#
(Optional) Check it first: nginx -t
You can simply use command nginx -s reload
to reload config, or restart the service service nginx restart
.
And finished.
Now when you access the path of website, it will show such the input box:
References#
- 《How To Set Up Password Authentication with Nginx on Ubuntu 14.04 | DigitalOcean》https://www.digitalocean.com/community/tutorials/how-to-set-up-password-authentication-with-nginx-on-ubuntu-14-04