A simple demo of using Nginx as a reverse proxy to add basic authentication.
-
-
Save concosminx/06bb9518d9fbcdc5f786f72d7b2073db to your computer and use it in GitHub Desktop.
Nginx reverse proxy with basic authentication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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