Skip to content

Instantly share code, notes, and snippets.

@laurentbel
Last active September 21, 2024 12:05
Show Gist options
  • Save laurentbel/c4c7696890fc71c8061172a932eb52e4 to your computer and use it in GitHub Desktop.
Save laurentbel/c4c7696890fc71c8061172a932eb52e4 to your computer and use it in GitHub Desktop.
Nginx reverse proxy with basic authentication

Nginx Basic Auth

A simple demo of using Nginx as a reverse proxy to add basic authentication.

services:
application:
image: httpd
networks:
- mynetwork
nginx:
image: nginx-basic-auth
ports:
- "80:80"
depends_on:
- application
environment:
- FORWARD_HOST=application
- FORWARD_PORT=80
- BASIC_USERNAME=john.doe
- BASIC_PASSWORD=myp@ssword!
networks:
- mynetwork
networks:
mynetwork:
FROM nginx:1.19
# Install apache2-utils to get htpasswd command
RUN apt-get update -y && apt-get install -y apache2-utils && rm -rf /var/lib/apt/lists/*
# Basic auth credentials
ENV BASIC_USERNAME=username
ENV BASIC_PASSWORD=password
# Forward host and foward port as env variables
# google.com is used as a placeholder, to be replaced using environment variables
ENV FORWARD_HOST=google.com
ENV FORWARD_PORT=80
# Nginx config file
WORKDIR /
COPY nginx-basic-auth.conf nginx-basic-auth.conf
# Startup script
COPY run.sh ./
RUN chmod 0755 ./run.sh
CMD [ "./run.sh" ]
server {
listen 80 default_server;
location / {
auth_basic "Restricted";
auth_basic_user_file .htpasswd;
proxy_pass http://${FORWARD_HOST}:${FORWARD_PORT};
proxy_read_timeout 900;
}
}
#!/bin/sh
# nginx config variable injection
envsubst < nginx-basic-auth.conf > /etc/nginx/conf.d/default.conf
# htpasswd for basic authentication
htpasswd -c -b /etc/nginx/.htpasswd $BASIC_USERNAME $BASIC_PASSWORD
nginx -g "daemon off;"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment