Enable the authorization (password-protected) page on Nginx (Ubuntu).
In many scenarios, we may not want a particular page or directory to be accessed by unauthorized users or crawled by bots. Nginx provides an option to restrict access to specific directories using password authentication. This guide explains how to configure a password-protected page on an Nginx web server running on Ubuntu.
Introduction
Nginx supports HTTP Basic Authentication to protect specific directories or pages. In this example, the web directory is protected using a username and password stored in an .htpasswd file.
If Nginx is not installed on the server, install and configure Nginx before proceeding with this guide.
Prerequisites
- Ubuntu server
- Nginx web server installed
- Root or sudo access
- Access to the Nginx configuration file
- A directory that needs to be password protected
Implementation
Step 1
Assume that the web directory needs to be protected with a password and there is only one domain configured on the server.
The Nginx configuration file is:
/etc/nginx/sites-enabled/default
For a domain-specific configuration, edit the appropriate domain configuration file.
Step 2
Open the Nginx configuration file using your preferred editor.
vi /etc/nginx/sites-enabled/default
Step 3
Add the following configuration inside the server block.
location /web/ {
auth_basic "Restricted Content";
auth_basic_user_file /var/www/html/web/.htpasswd;
}
The auth_basic_user_file directive specifies the location of the file used to store the authentication credentials.
In this example, the password file is located at:
/var/www/html/web/.htpasswd
You can use a different location if you want to keep the password file outside the document root.
Step 4
Create the .htpasswd file using the htpasswd command.
htpasswd -c /var/www/html/.htpasswd username
Enter the password when prompted.
New password: Re-type new password: Adding password for user username
Step 5
If the htpasswd command is not available, install the apache2-utils package.
apt-get install apache2-utils
After installation, run the htpasswd command again.
Step 6
Check the Nginx configuration for syntax errors.
nginx -t
A successful configuration test should display:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Step 7
Restart the Nginx service to apply the changes.
systemctl restart nginx
Step 8
Access the protected page from a browser.
http://IPADDRESS/web
The browser will display an authorization prompt requesting the configured username and password.
Conclusion
Password-protecting a directory using Nginx provides a simple way to restrict access to specific website content. After configuring HTTP Basic Authentication and the .htpasswd file, users must provide valid credentials to access the protected directory.
