Implement Basic Authentication in Nginx to restrict access to specific web pages.
Basic Authentication sends username and password in plain text. Therefore, it is crucial to use a secure connection with SSL/TLS. Refer to the SSL/TLS configuration section for details.
Set up Basic Authentication on the desired site configuration.
Install httpd-tools for managing password files:
[root@www ~]# dnf -y install httpd-tools
Edit the Nginx configuration file to add Basic Authentication settings:
[root@www ~]# vi /etc/nginx/conf.d/ssl.conf
# Add the following inside the server block:
server {
.....
.....
location /auth-basic/ {
auth_basic "Basic Auth";
auth_basic_user_file "/etc/nginx/.htpasswd";
}
}
[root@www ~]# systemctl reload nginx
Create a username and password for Basic Authentication:
[root@www ~]# htpasswd -c /etc/nginx/.htpasswd cent
# Set and confirm the password when prompted
Set up a test page to verify the Basic Authentication:
[root@www ~]# mkdir /usr/share/nginx/html/auth-basic
[root@www ~]# vi /usr/share/nginx/html/auth-basic/index.html
# Add the following HTML content:
<html>
<body>
<div style="width: 100%; font-size: 40px; font-weight: bold; text-align: center;">
Test Page for Basic Authentication
</div>
</body>
</html>
Access the test page from a web browser:
http://yourdomain.com/auth-basic/.Ensure that the authentication process works correctly: