Using the Nginx Basic Authentication Module
The ngx_http_auth_basic_module
in Nginx allows us to use basic authentication. This module can be used to protect certain paths and resources in your website from unauthorized access. By using this module, you will need to create a file containing usernames and passwords and add it to your Nginx server configuration.
Setting up this module requires a few simple steps. First, you need to create a file with the usernames and passwords. Then, you can add this file to Nginx and specify specific paths that require authentication. This can particularly be useful for sensitive resources like admin panels or sensitive content.
Now, let’s take a look at how to create the authentication file and configure it in Nginx. Make sure that the ngx_http_auth_basic_module
is enabled in your Nginx. This module is usually available by default in Nginx, but if needed, you can install it using special distributions of Nginx.
In the end, by implementing these configurations, you can protect your website from unauthorized users and ensure your information is safe. Now let's write some code!
# Creating the authentication file
htpasswd -c /etc/nginx/.htpasswd username
# Nginx configuration to use basic authentication
server {
listen 80;
server_name example.com;
location /protected {
auth_basic "Restricted Content";
auth_basic_user_file /etc/nginx/.htpasswd;
}
}
Code Explanations
Creating the authentication file: htpasswd -c /etc/nginx/.htpasswd username
This command creates a new file named .htpasswd
in the directory /etc/nginx/
and adds a user named username
to this file.
Nginx Configuration: server { ... }
This block defines an Nginx server that responds to requests. Here, it binds the server to port 80 and assigns the domain example.com
.
Protected Location: location /protected { ... }
This section specifies that the path /protected
requires authentication.
Basic Authentication: auth_basic "Restricted Content";
This line specifies the title dialog for basic authentication that the user will see.
User file location: auth_basic_user_file /etc/nginx/.htpasswd;
This points to the file .htpasswd
that contains usernames and passwords.