HTTP Basic Authentication on Localhost (Nginx on Mac)
· Nginx & Infra · By Zeeshan Ahmad
How to Set Up HTTP Basic Authentication on Localhost:8080 Nginx on Mac
Problem
HTTP Basic Authentication is a simple yet effective way to secure access to web resources by requiring a username and password. This guide will help you set up HTTP Basic Authentication on an Nginx server running on localhost:8080 on a Mac.
Solution
-
Step 1: Install Nginx and Apache Utils
If you haven't installed Nginx, use Homebrew to install it:
bashbrew install nginxApache Utils provides the
htpasswdutility required to create password files:bashbrew install apache2-utils -
Step 2: Create a Password File
Use the
htpasswdutility to create a password file:bashsudo htpasswd -c /usr/local/etc/nginx/.htpasswd usernameTo add more users, run the following command without the
-cflag:bashsudo htpasswd /usr/local/etc/nginx/.htpasswd additionaluser -
Step 3: Configure Nginx
Edit the Nginx configuration file to include the authentication directives:
bashsudo nano /usr/local/etc/nginx/nginx.confAdd the following lines inside the
httpblock, within theserverblock that listens on port8080:nginxserver { listen 8080; server_name localhost; location / { auth_basic "Restricted Area"; auth_basic_user_file /usr/local/etc/nginx/.htpasswd; root html; index index.html index.htm; } } -
Step 4: Test the Configuration
Check the Nginx configuration for syntax errors:
bashsudo nginx -tIf the syntax is correct, restart Nginx to apply the changes:
bashsudo nginx -s reload
Conclusion
HTTP Basic Authentication provides a straightforward way to protect web resources by requiring a username and password. By following these steps, you can set up HTTP Basic Authentication on an Nginx server running on localhost:8080 on your Mac, enhancing the security of your local web applications.