Password protecting a site in nginx
This post will explain how to password protect a site in nginx. It is very simple and it uses the normal htpasswd protection
Suppose I need to password protect the site abc.com whose document root is /var/www/abc/public_html
Simple follow the steps given below
[root@abc ~]# cd /var/www/abc/public_html
[root@abc ~]# htpasswd -c .htpasswd admin where admin is the username chosen. It will prompt for password, give a strong password.
Now, your login details are stored to the file /var/www/abc/public_html/.htpasswd and we need to call this file from abc.com’s conf.
Simply add the following two lines before the locations
[root@abc ~]# cd /etc/nginx/sites-available/
[root@abc ~]# vi abc.com
auth_basic “Restricted”;
auth_basic_user_file /var/www/abc/public_html/.htpasswd;
So your final conf will now look as follows.
server {
server_name www.abc.com abc.com;
access_log /var/www/abc/logs/access.log;
error_log /var/www/abc/logs/error.log;
root /var/www/abc/public_html/;
auth_basic “Restricted”;
auth_basic_user_file /var/www/abc/public_html/.htpasswd;
location / {
index index.html index.htm index.php;
}
location ~ \.php$ {
if (!-e $request_filename) { rewrite / /index.php last; }
include /etc/nginx/fastcgi_params;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /var/www/abc/public_html$fastcgi_script_name;
fastcgi_param MAGE_RUN_CODE base;
fastcgi_param MAGE_RUN_TYPE website;
}
}
All done, save the configuration file and exit. Now restart nginx and see if it starts without errors.
[root@abc ~]# /etc/rc.d/init.d/nginx restart
Stopping nginx: [ OK ]
Starting nginx: [ OK ]
Now clear your browser cache and try accessing the site. Bingo!! isnt’t it protected? ![]()
Leave a Reply