In the name of God
This gist describes how to setup password protect web directories in Nginx docker containers.
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 >> htpasswdYou can repeat this process for additional usernames. You can see how the usernames and encrypted passwords are stored within the file:
$ cat htpasswdOutput:
sammy:$apr1$XlI6K26R$qJqpz3GDwVOH4EUxCJf4u0Create 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;
}
}
$ 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 \
nginxYou 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 \
nginxOpen http://localhost:8080 in your browser and confirm the password authentication (for example: sammy for username and 123456 for password).