Nginx reverse proxy with authentication how to

Reverse proxy is used to take the load of the server by caching the request , Sometimes can be the case where we require authentication to come before any user can access a domain where we require nginx reverse proxy with authentication.

Nginx (Spelled Engine-X) is a free open source ,  high performance web server which can also act as a reverse proxy as well as an IMAP/POP3 proxy server , It uses very efficient event driven asynchronous architecture, It can handle thousand of requests simultaneously with very low memory footprint.

Nginx reverse proxy with authentication how to

1. Install Nginx

In Ubuntu/Debian

# aptitude install nginx

In Cent-OS?redhat/Fedora

#yum install nginx

Or either you can access and download and compile the packages if it is not available in your repository.

2. Create proxy configuration file defining rule for headers and other configuration variables, Open vi editor and create proxy.conf

 # vi /etc/nginx/conf.d/proxy.conf

Append the following 

proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 10m;
client_body_buffer_size 128k;
proxy_connect_timeout 90;
proxy_send_timeout 90;
proxy_read_timeout 90;
proxy_buffers 32 4k;

These values should work for you

3. Create configuration for web domain which will tell the domain to run it as a reverse proxy and the source url from which it will pick it. Supposing the domain is for which you are creating reverse proxy we will create a configuration file

# vi /etc/nginx/conf.d/

server {
listen 80;
access_log /var/log/nginx.access.log;
error_log /var/log/nginx_error.log debug;
location / {
auth_basic "Restricted"; #For Basic Auth
auth_basic_user_file /etc/nginx/.htpasswd; #For Basic Auth
include conf.d/proxy.conf;

These above two lines tell nginx to enable authentication using the credential stored in htaccess file.

4. Create authentication file , supposing we need to add authentication for user maverick , we will follow the below steps

# htpasswd -c /etc/nginx/.htpasswd maverickNew password: 
Re-type new password:

5. Make entry in hosts file

If the ip address of the backend(original server) is (running , remember to make the entry in hosts file

#vi /etc/hosts
Add the following host entry :-


6. Start Nginx service and you are ready to go# vi /etc/hosts

# /etc/init.d/nginx start

If you face any problem or have any question , I will be happy to serve you