How to Harden NGINX Server

Last updated on September 9th, 2024 at 05:03 am

NGINX is one of the most popular web servers used by millions of websites and applications. Therefore, it is a constant target of online attacks. So it is important to secure NGINX server to protect itself from malicious attacks. Otherwise, user and bots may gain unauthorized access to your server and compromise your website. Here’s how to harden NGINX server so that your websites and apps run well. You can use them for NGINX server hardening and for hardening NGINX reverse proxy.

How to Harden NGINX Server

Here are the steps to harden NGINX server.

1. Disable Server Tokens

Server token is server signature information that is displayed on error pages such as 404 response pages. It allows attackers to figure out your NGINX server version and exploit its vulnerabilities.

So you need to disable server tokens in NGINX server by adding server_tokens directive inside a server block as shown.

server{
   ...
   server_tokens off;
   ...
}

Restart NGINX to apply changes.

Bonus Read : How to Implement NGINX Reverse Proxy

2. Block HTTP User Agents

Certain user agent bots are malicious and can waste your system resources with slow and data heavy requests. So it is important to block them upfront.

Create a black list file /etc/nginx/blockuseragents.rules with the following information about common malicious bots

$ sudo vi /etc/nginx/blockuseragents.rules

Add the following configuration

 map $http_user_agent $blockedagent { 
      default 0; 
      ~*malicious 1; 
      ~*bot 1;
      ~*backdoor 1; 
      ~*crawler 1; 
      ~*bandit 1; 
}

Save & Exit the file.

Next, include this file in your NGINX server configuration and place it before the server block

include /etc/nginx/blockuseragents.rules;

Now these bots will get a 403 : Access Forbidden response when they access your website.

Bonus Read : How to Block IP Address in NGINX

3. Disable unnecessary HTTP methods

Most websites use GET, POST and HEAD request methods. However, malicious attackers can send DELETE requests to try and exploit your server vulnerabilities.

So it is important to allow only GET, POST and HEAD requests and disable all other requests. Add the following lines in your server block to send an empty response code 444 to any request other than GET, POST and HEAD.

if ($request_method !~ ^(GET|HEAD|POST)$) {
   return 444;
}

Restart NGINX server to apply changes. Now if you try sending a DELETE request to NGINX server, you will get an empty response.

# curl -X DELETE http://192.168.0.25/index.html
curl(52) : Empty response from server

4. Prevent Image Hotlinking

Image hotlinking is when other websites link to images on your website from their domain. So every time their page is loaded, then image is served from your server, and costs you unnecessary data bandwidth.

Let’s say your website images are stored at /images subfolder. To prevent others from hotlinking these images, add the following location block to your NGINX configuration or virtual host configuration file.

location /images/ {
   valid_referers none blocked 243.34.54.65;
   if ($invalid_referer) {
      return 403;
   }
}

The above code will return 403 response code for all requests except the ones sent from IP 243.34.54.65. You can replace this IP with your IP or domain name. Here is our detailed article to prevent image hotlinking.

5. Use SSL certificates

One of the most important tips to harden NGINX server is to use SSL certificates. First, generate a key and certificate using openSSH or any other encryption tool.

# openssl genrsa -aes256 -out nginx.key 1024
# openssl req -new -key nginx.key -out nginx.csr
# cp nginx.key nginx.key.org
# openssl rsa -in nginx.key.org -out nginx.key
# openssl x509 -req -days 365 -in nginx.csr -signkey nginx.key -out nginx.crt

The above commands will create key and certificate. Add their paths to your server block that listens to port 443 (SSL port).

server {
   listen 443 ssl;
   ...

   ssl_certificate /etc/nginx/sites-enabled/certs/nginx.crt;
   ssl_certificate_key /etc/nginx/sites-enabled/certs/nginx.key;
   ...
}

You can also purchase SSL certificates from third-party providers such as RapidSSL, Comodo, Verisign, GeoTrust, etc.

6. Enable TLS 1.3 in NGINX

After you have set up SSL certificates, enable TLS v1.3 in NGINX since it is the most secure protocol yet. You can do this by adding ssl_protocols directive to your server block in the previous step.

server{
   listen 443;
   ...
   ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3;
   ...
}

In fact, it is advisable to omit TLSv1, TLSv1.2 and TLSv1.3 from the above configuration to completely stop supporting older insecure protocols.

7. Redirect HTTP to HTTPS

It is important to redirect all HTTP requests to HTTPS port (443). This not only improves website security but also improves its search engine rankings. Add the following line to server block that listens to port 80 (HTTP port).

server{
   listen 80;
   ...
   return 301 https://$server_name$request_uri;
}

In the above code, we define a server block that listens to HTTP port 80. All requests received on this port are permanently redirected to HTTPS port 443 using ‘return 301’ directive.

We have assumed that you already have another server block defined in your server configuration that is listening to HTTPS port 443.

server{
    listen 443;
}

Bonus Read : How to Redirect Subdomain to Folder in NGINX

After you have made the above changes, restart NGINX web server to apply changes.

Restart NGINX server to apply changes

# nginx -t
# systemctl restart nginx.service

8. Disable Unwanted Modules

NGINX supports tons of useful modules that help you perform different tasks in your server. But over time, some of them become outdated and irrelevant. If you do not remove them, attackers can exploit any vulnerabilities that are present in them. Here are the commands to disable an NGINX module.

# ./configure --without-<module name>
# make 
# make install

Here is an example to disable autoindex module.

# ./configure --without-http_autoindex_module 
# make 
# make install

9. Install ModSecurity

ModSecurity is a free firewall popularly used by many system administrators to protect their server and other applications. It allows you to easily monitor, filter and block requests and responses. It also provides advanced features such as server masking and null-byte attack prevention. Here is our detailed step by step tutorials to install and configure ModSecurity for NGINX.

10. Disable IFrames

IFrames allow users to display your web pages on their website, without your permission. Most websites do not need this feature, so it is advisable to disable it. It also leads to clickjacking attacks. Therefore, add the following response header in your server, or location blocks to indicate to web browser that they are allowed to render the response only if the present website has the same domain as the requested domain.

location / {
     add_header X-Frame-Options "SAMEORIGIN";
}

11. Enable Strict Transport Policy

In addition to enabling SSL/TLS certificates, you can also enable HTTP Strict Transport Security (HSTS). If a web browser has HSTS defined, then web browsers are required to send requests only via HTTPS protocol. Even if a user or bot requests an HTTP URL, it will be automatically refused by the web browser. For this purpose, add the following line to server or location block.

location / {
   add_header Strict-Transport-Security "max-age=31536000; includeSubdomains; preload";
}

12. Update NGINX Server Regularly

Every NGINX update contains loads of security updates and patches that are essential to protect your server. Therefore, it is advisable to regularly update your NGINX server so that you do not miss out on any important fixes.

12. Monitor NGINX Server Logs

NGINX mainly uses 2 kinds of server logs – one for logging each request, called access.log and the other to log each error, called error.log.

It is important to regularly monitor these log files to discover frequent errors that you need to fix ASAP, and also any malicious requests that you need to block. It also helps you identify suspicious IPs that you may need to block. There are many free and paid log management tools that you can use to monitor NGINX server.

13. Prevent Content Theft & XSS Attacks

Cross Site Scripting (XSS) is a common attack where your server receives malicious script that is automatically injected into your server via HTML forms and other user inputs. These scripts are stored in your site’s database and read-back when your web page is rendered, causing this script to execute on client browser. This can be used to damage your site as well as steal user credentials. Therefore, it is important to prevent it. You can do this by setting content security policy header in server or location block.

location / {
      add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;
      }

The above header is not supported by older web browsers. In their case, you need to use the following header instead.

location / {
      add_header X-XSS-Protection "1; mode=block";
      }

14. Use Less Privileged User

Every application including NGINX server needs a system user to be able to access various files and run commands on your system. In NGINX, this is defined using ‘user’ server directive.

user <username>

For this purpose, use a user that is non-root and non-privileged. Typically, system administrators create a separate user nginx for web server and use it.

user nginx;

15. Set Correct File Permissions

It is important to give NGINX installation the correct permissions so that even if someone gets access to it, they are unable to cause significant damage to your website. You can control file ownership and permission using chmod and chown commands respectively.

$ chown -R nginx:nginx /path/to/nginx
$ chmod -R 750 /path/to/nginx

Conclusion

In the article, we have learnt several different ways to harden NGINX web server. There is no one stop solution for this problem. You need to systematically implement each of the above solutions to secure your server. Also, you need to keep yourself up to date about the latest developments in NGINX server, since every new feature or update can open up potential security threats. Nevertheless, we hope that the above techniques will help you secure your NGINX server from malicious users and bots.

Ubiq makes it easy to visualize data in minutes, and monitor in real-time dashboards. Try it Today!