Configure Nginx to restrict access to a specific location using both access lists and Basic Authentication.
-
Install Nginx:
- If you haven't installed Nginx, do so based on your operating system. For example:
- Ubuntu/Debian:
sudo apt-get install nginx
- CentOS:
sudo yum install nginx
- Ubuntu/Debian:
- If you haven't installed Nginx, do so based on your operating system. For example:
-
Install
apache2-utils
package:- The
htpasswd
utility is part of theapache2-utils
package. Install it using:- Ubuntu/Debian:
sudo apt-get install apache2-utils
- CentOS:
sudo yum install httpd-tools
- Ubuntu/Debian:
- The
-
Create a Basic Authentication File:
-
Use the
htpasswd
utility to create a file with the username and hashed password.sudo htpasswd -c /etc/nginx/.htpasswd user1
-
-
Edit Nginx Configuration:
-
Open the Nginx configuration file for editing.
sudo nano /etc/nginx/nginx.conf
-
Add the following configuration inside the
http
block:server { listen 80; server_name your-domain.com; location /private { auth_basic "Restricted Access"; auth_basic_user_file /etc/nginx/.htpasswd; allow 192.168.1.0/24; deny all; } }
-
Adjust network range according to the address where you are:
-
-
Save and Close:
- Save the configuration file and close the text editor.
-
Test Access:
-
Open a web browser and try to access the
/private
location on your server. You should be prompted for credentials. -
Use the username
user1
and the password you set during thehtpasswd
creation.echo "127.0.0.1 your-domain.com" | sudo tee /etc/hosts sudo nginx -t sudo systemctl reload nginx
-
-
Verify Access List:
- Test access from both the allowed IP range (192.168.1.0/24) and a denied IP range to ensure that access lists are working as expected.
-
Cleanup:
- Remove added configuration from point
4
.