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

  1. Step 1: Install Nginx and Apache Utils

    If you haven't installed Nginx, use Homebrew to install it:

    brew install nginx

    Apache Utils provides the htpasswd utility required to create password files:

    brew install apache2-utils
  2. Step 2: Create a Password File

    Use the htpasswd utility to create a password file:

    sudo htpasswd -c /usr/local/etc/nginx/.htpasswd username

    To add more users, run the following command without the -c flag:

    sudo htpasswd /usr/local/etc/nginx/.htpasswd additionaluser
  3. Step 3: Configure Nginx

    Edit the Nginx configuration file to include the authentication directives:

    sudo nano /usr/local/etc/nginx/nginx.conf

    Add the following lines inside the http block, within the server block that listens on port 8080:

    server {
        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;
        }
    }
  4. Step 4: Test the Configuration

    Check the Nginx configuration for syntax errors:

    sudo nginx -t

    If the syntax is correct, restart Nginx to apply the changes:

    sudo nginx -s reload
To start httpd now and restart at login: brew services start httpd Or, if you don't want/need a background service you can just run: /usr/local/opt/httpd/bin/httpd -D FOREGROUND

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.