Securing our Nginx proxy server

This is the most important piece in the Nginx setup. In this section, we will look at how to restrict access to our server using basic authentication. This is very important for our REST API servers because, suppose we have servers XY, and Z that can talk to each other. X can serve clients directly, but X consults Y and Z for some information by calling an internal API. We should prevent clients from accessing Y and Z. We can allow or deny IP addresses using the nginx access module. It looks like this:

location /api {
...
deny 192.168.1.2;
allow 192.168.1.1/24;
allow 127.0.0.1;
deny all;
}

This configuration tells Nginx to allow requests from clients ranging 192.168.1.1/24, excluding 192.168.1.2. The next line tells us to allow requests from the same host and block all other requests from any other client. The complete server block looks like this:

server {
listen 80 default_server;
root /usr/share/nginx/html;

location /api {

deny 192.168.1.2;
allow 192.168.1.1/24;
allow 127.0.0.1;
deny all;
}
}

For more information regarding this, you can refer to the documentation at http://nginx.org/en/docs/http/ngx_http_access_module.html?_ga=2.117850185.1364707364.1504109372-1654310658.1503918562. We can also add password-secured access to our Nginx serving static files. It is mostly not applicable to the API because there, the application takes care of authenticating the user. The whole idea is to only allow the IP that is approved by us and deny all other requests.

Nginx can only serve requests when the application server's health is good. If the application crashes, we have to restart it manually. A crash can occur from a system shutdown, a problem in the network storage, or various other external factors. In the next section, we will discuss a process monitoring tool called supervisord that can automatically restart a crashed application.