Skip to content

Instantly share code, notes, and snippets.

@bholagabbar
Created September 9, 2023 15:52
Show Gist options
  • Save bholagabbar/2a4ac361362c8137abe010511c8c1016 to your computer and use it in GitHub Desktop.
Save bholagabbar/2a4ac361362c8137abe010511c8c1016 to your computer and use it in GitHub Desktop.
Nginx Basic Auth

1. Install Nginx

If you haven't installed Nginx already, do so with:

sudo apt update
sudo apt install nginx

2. Setup Basic Authentication

For basic authentication, you'll create a password file. The htpasswd tool from the apache2-utils package will help:

sudo apt install apache2-utils

Now, create a user and password. This will create a new file with the user and the encrypted password:

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

You'll be prompted to enter and confirm your password.

3. Modify the Default Nginx Configuration to Route to Your Service

Open the default configuration:

sudo nano /etc/nginx/sites-available/default

Now, within the server block, add or modify the location directive:

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    ...

    location /your-url {
        proxy_pass http://localhost:42110;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;

        # Basic Auth setup
        auth_basic "Restricted Content";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }

    ...
}

Save and exit the editor (in nano, it's CTRL+X to close, Y to confirm changes, and Enter to save).

Test the configuration to ensure there are no syntax errors:

sudo nginx -t

If the configuration test is successful, restart Nginx to apply the changes:

sudo systemctl restart nginx

Now, when you try to access http://your_server_ip/your-url, Nginx will prompt you for the username and password. Once authenticated, you'll be routed to the service running on localhost:42110.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment