Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save amir-saniyan/e4ff4af4318ee5b7dd4947ded3339be6 to your computer and use it in GitHub Desktop.
Save amir-saniyan/e4ff4af4318ee5b7dd4947ded3339be6 to your computer and use it in GitHub Desktop.
server {
listen 80;
listen [::]:80;
server_name localhost;
#access_log /var/log/nginx/host.access.log main;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
autoindex on;
charset utf-8;
auth_basic "Restricted Content";
auth_basic_user_file /etc/nginx/htpasswd;
}
}
sammy:$apr1$XlI6K26R$qJqpz3GDwVOH4EUxCJf4u0

Password Protect Web Directories in Nginx Docker Containers

In the name of God

This gist describes how to setup password protect web directories in Nginx docker containers.

Step 1: Create Password File

To create the password file using the OpenSSL utilities, run the following command in terminal:

# Username: sammy, but you can use whatever name you’d like
# Password: <Type the password, for example 123456>
$ echo -n 'sammy:' >> htpasswd
$ openssl passwd -apr1 >> htpasswd

You can repeat this process for additional usernames. You can see how the usernames and encrypted passwords are stored within the file:

$ cat htpasswd

Output:

sammy:$apr1$XlI6K26R$qJqpz3GDwVOH4EUxCJf4u0

Step 2: Create Nginx Configuration File

Create default.conf file with the following contents:

server {
    listen       80;
    listen  [::]:80;
    server_name  localhost;

    #access_log  /var/log/nginx/host.access.log  main;

    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        autoindex on;
        charset utf-8;
        auth_basic "Restricted Content";
        auth_basic_user_file /etc/nginx/htpasswd;
    }
}

Step 3: Running Docker Container

$ docker container run \
    --name http-server \
    --volume $(pwd)/default.conf:/etc/nginx/conf.d/default.conf:ro \
    --volume $(pwd)/htpasswd:/etc/nginx/htpasswd:ro \
    --volume $(pwd):/usr/share/nginx/html:ro \
    --publish 8080:80 \
    --interactive \
    --tty \
    --rm \
    nginx

You may change $(pwd) with your specified directory, for example:

$ docker container run \
    --name http-server \
    --volume /home/sammy/Documents/default.conf:/etc/nginx/conf.d/default.conf:ro \
    --volume /home/sammy/Documents/htpasswd:/etc/nginx/htpasswd:ro \
    --volume /home/sammy/Documents:/usr/share/nginx/html:ro \
    --publish 8080:80 \
    --interactive \
    --tty \
    --rm \
    nginx

Step 4: Browse Password Protect Directories

Open http://localhost:8080 in your browser and confirm the password authentication (for example: sammy for username and 123456 for password).

Resources

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