Securing Nginx sites with Basic Auth
Creating user
- Install
apache2-utils
for (Debian, Ubuntu) orhttpd-tools
for (RHEL/CentOS/Oracle Linux). Verifyhtpasswd
command exists. - Create a new user with
htpasswd
command.
sudo htpasswd -c /etc/nginx/.htpasswd sam
# -c creates new file
- Verify if the new user has been created.
cat /etc/nginx/.htpasswd
- To add other users, run the following, replace smith with your desired username.
sudo htpasswd /etc/nginx/.htpasswd smith
Adding Basic Auth for a site
- Go to your desired site in sites-available.
- To add the auth for a specific block, add the following inside the location block.
location /status {
auth_basic "Administrator’s Area";
auth_basic_user_file /etc/nginx/.htpasswd;
stub_status ;
}
- To add the auth for the whole site, you can add it directly in the server block. And you can turn off the auth for specific location as below.
server {
...
auth_basic "Administrator’s Area";
auth_basic_user_file conf/htpasswd;
location /public/ {
auth_basic off;
}
}
Reference:
Original Nginx Guide: https://docs.nginx.com/nginx/admin-guide/security-controls/configuring-http-basic-authentication/