Secure Nginx

Guide how to secure your Nginx web server.

There are a few steps you can take to secure your Nginx web server.

Disable unused Nginx modules

Disable unused Nginx modules by recompiling Nginx without the modules you do not need.

By default, Nginx comes with preinstalled modules that you may not need for your project. Disable unused Nginx modules in order to reduce the attack surface.

  1. Uninstall Nginx if it's already installed

  2. Download the uncompiled Nginx version to build it from source

  3. Run ./configure along with the modules you do not want to install. Here's an example:

     ./configure --without-http_map_module
     make
     make install

Disable server_tokens

The server_tokens parameter outputs the Nginx version in each HTTP response header.

Disable server_tokens by following these steps:

  1. Edit the nginx.conf file:

     vi /etc/nginx/nginx.conf
  2. Add the server_tokens parameter with the off value in the server { } block directive.

     server {
        listen 127.0.0.1:80;
        server_name mydomain.com;
        
        server_tokens off;
     }
  3. Restart Nginx:

     sudo systemctl restart nginx

Disable unused HTTP methods

You can disable unused HTTP methods such as DELETE, TRACK, TRACE and keep only the common HTTP methods used: GET, POST, HEAD.

  1. Edit the nginx.conf file:

     vi /etc/nginx/nginx.conf
  2. Add the following directive in the server { } block directive:

     server {
        if ($request_method !~ ^(GET|HEAD|POST)$) {
            return 405;
        }
     
        # other lines
     }

    This code snippet will return HTTP error code 405 (Method Not Allowed) if the HTTP method is not GET, POST or HEAD.

  3. Restart Nginx:

     sudo systemctl restart nginx