Whenever there was requirement to protect a webiste or a particular folder in website with some username and password, we are used to do it with Apache2/Apache HTTP.
This time I thought to try with Nginx.
Here I am proxy passing all requests with upstream and I wanted to protect it some username and password.
Again I used apach2-utils module to protect website.
Install apache2-utils:
$ apt-get install apache2-utils
Now create a user with some password:
$ htpasswd -c /etc/nginx/conf.d/.htpasswd/passwd username
where username is some username as you wish, it will ask for password just enter some password.
After creating usename and password add following configuration nginx.conf’s http module.
upstream appcluster {
server 192.168.2.20:8080;
}
server {
listen *;
location / {
proxy_pass http://appcluster;
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/conf.d/.htpasswd/passwd;
proxy_set_header X-Real-IP $remote_addr;
}
Upstream module will proxy pass all request that are coming to your hostname to port 8080 of ip 192.168.2.20.
After adding above configuration restart nginx and try to access you hostname, it should ask username and password.
In above configuration following 2 lines are responsible for protecting your website:
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/conf.d/.htpasswd/passwd;
After adding all configurations in nginx.conf, following is my http module:
http {
##
# Basic Settings
##
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
##
# Logging Settings
##
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
##
# Gzip Settings
##
gzip on;
gzip_disable "msie6";
upstream appcluster {
server 192.168.2.20:8080;
}
server {
listen *;
location / {
proxy_pass http://appcluster;
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/conf.d/.htpasswd/passwd;
proxy_set_header X-Real-IP $remote_addr;
}
}
}