How to Set Up HTTP Basic Authentication in Nginx (Linux)
· Nginx & Infra · By Zeeshan Ahmad
How to Set Up HTTP Basic Authentication in Nginx
Problem
HTTP Basic Authentication is a simple authentication mechanism built into the HTTP protocol. It requires users to provide a username and password to access certain resources. This guide will walk you through setting up HTTP Basic Authentication in Nginx to secure your web applications.
Solution
-
Step 1: Install the Apache Utils Package
bashsudo apt-get update sudo apt-get install apache2-utilsbashsudo yum install httpd-tools -
Step 2: Create a Password File
bashsudo htpasswd -c /etc/nginx/.htpasswd username sudo htpasswd /etc/nginx/.htpasswd additionaluser -
Step 3: Configure Nginx to Use the Password File
nginxserver { listen 80; server_name your_domain.com; location / { auth_basic "Restricted Area"; auth_basic_user_file /etc/nginx/.htpasswd; proxy_pass http://your_backend_server; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } -
Step 4: Test the Configuration
bashsudo nginx -t sudo systemctl reload nginx
Conclusion
HTTP Basic Authentication provides a straightforward way to protect web resources by requiring a username and password. By following these steps, you can easily set up HTTP Basic Authentication in Nginx to enhance the security of your web applications.