Basic authentication with Nginx requires an installation of Nginx and htpasswd. We have to create a password file with users and passwords and add this file to Nginx.
The password file
The first step is the creation of a password file with htpasswd tool using the following command:
htpasswd -c .htpasswd user
The flag -c is used to create a file, the next parameter is the file name (you can set the absolute path where the file should be created, or as the example above use the current directory) and the last parameter is the user we want to create. After execution of the command, you will be prompted to enter and confirm a password for the user. You can add additional users using the same command without the flag for file creation (-c).
Config Nginx
To activate Nginx basic authentication you need to add these lines in your section which you want to control (in the example it is server section) for example:
auth_basic "My Private Area";
auth_basic_user_file path/to/.htpasswd;
Parameter auth_basic contains the name of the area and auth_basic_user_file contains the path to the password file that we created.
For example my config file looks like:
server{
listen 6000;
listen [::]:6000;
server_name _;
auth_basic "My Private Area";
auth_basic_user_file /etc/nginx/.htpasswd;
location / {
proxy_pass http://127.0.0.1:8800/;
}
}
The configuration redirects traffic from port 6000 to 8800 and requires basic authentication.
Note: All commands are executed as root.
Leave A Comment