Tuesday, March 29, 2016

Add simple HTTP Basic Authentication using Nginx

Protecting your website from public using Nginx using Basic HTTP Authentication is easy.

This example uses Nginx + FPM and PHP5

This is useful when you just need to have simple protection for the following purposes:

1. During development.
2. Private website.
3. Temporary protection for certain directories.

Where to implement Basic HTTP Authentication in Nginx?


Inside your virtual host / default host configuration file.
In this example I am using Ubuntu and default configuration, so my default host configuration file is located at:

/etc/nginx/sites-available/default

Add the following lines inside the location ~ \.php$ { .... } block.

auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;

My entire location block looks like this:

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
auth_basic "Restricted";
auth_basic_user_file /etc/nginx/.htpasswd;

fastcgi_buffer_size 128k;
fastcgi_buffers 4 256k;
fastcgi_busy_buffers_size 256k;

fastcgi_split_path_info ^(.+\.php)(/.+)$;
# NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini

# With php5-cgi alone:
fastcgi_pass 127.0.0.1:9000;

# With php5-fpm:
# fastcgi_pass unix:/var/run/php5-fpm.sock;

fastcgi_index index.php;
include fastcgi_params;
}



How to protect SSL (HTTPS) also with Basic HTTP Authentication in Nginx?

Just repeat the above steps while editing the HTTPS version of the configuration file.

In this example I edited:

/etc/nginx/sites-available/default-ssl

Create the .htpasswd (HTTP Password) file

DO NOT place this file inside your document root. I actually place mine in the Nginx configuration directory in:

/etc/nginx

I simply named the file:  .htpasswd

it is a . (dot) file because incase you accidentally place it inside your document root, typical web servers will not serve dot files.

Use online HTTP Password generators, just google 'http password generator'.

Here is the content of my .htpasswd file:

username:$apr1$YHsIoLBd$Ut5NoTL7bIIp9ysyLcczn.

the above line will allow username=username with password=password to be authenticated. 

Restart Nginx to apply your configuration

service nginx restart

No comments:

Post a Comment