Nginx Security Hardening Step by Step

Nginx Security Hardening Step by Step

Need to secure your Nginx? Here are the Nginx security tips to do so. Ensuring the security of your Nginx server is paramount to protect your web applications and sensitive data from potential threats. By implementing robust security measures, you can defend against a wide range of cyber attacks and vulnerabilities.

With Nginx powering 33.8% of all websites globally, it is one of the most popular and widely used web servers. However, this popularity also makes it a frequent target for cyber attackers. In fact, several critical vulnerabilities have been identified in Nginx over recent years, underscoring the importance of taking proactive security measures to safeguard your server​

Let’s dive into the essential tips and practices for hardening your Nginx server and maintaining a secure web environment.

Nginx Security

Nginx is a popular web server known for its performance, scalability and flexibility. But like any other web server it needs proper security configurations to protect against threats and attacks. Nginx hardening is a process of configuring the web server to increase its security features and prevent access to web applications and infrastructure.

Why Nginx Web Server Hardening?

Hardening your Nginx web server is to maintain the integrity and confidentiality of sensitive data. A secure Nginx configuration will prevent common web server vulnerabilities like buffer overflow attacks, cross-site scripting (XSS), cross-site request forgery (CSRF). By hardening your Nginx web server you can protect your web applications and infrastructure from cyber attacks and data breaches.

Nginx Security Hardening Checklist
Nginx Security Hardening Checklist

15 Steps to Secure your Nginx Server

Let’s deep dive into how to harden your Nginx server security step by step.

Update Your Nginx Server

Updating your Nginx server is for security and performance. Updates are not just for new features, they are to patch security holes that can be exploited by attackers. Nginx.org has a security advisories page where administrators can stay informed about potential threats and updates. Package managers will get the latest security patches for you so you reduce the risk of security breaches.

Monitoring security advisories will protect your Nginx server. These updates will not only patch known vulnerabilities but also general server resilience. Not updating your server will leave you open to attacks that exploit old software. So make it a habit to check for updates and apply them as soon as possible to have a secure server.

To update, use:

sudo apt update && sudo apt upgrade nginx

Disable Unwanted Nginx Modules

When securing your Nginx server, less is more. Disabling unwanted Nginx modules is a must. Many modules are included by default during installation but not all are necessary for your use case. Each enabled module is an attack vector so it’s better to limit the number of active modules to the minimum required for your server functionality. During nginx installation make sure to disable unwanted modules to increase security.

Recompile Nginx to disable specific modules, only the essentials. You can do this during installation using the configure nginx script. Choose the right modules to enable and reduce your server’s attack surface and security.

When installing Nginx, disable any unnecessary modules by recompiling with the desired modules. Use the following:

./configure --without-http_autoindex_module --without-http_empty_gif_module

This reduces the attack surface of your server. Restart Nginx to apply the changes.

Remember, a lean Nginx configuration is not only more secure but also faster.

SSL/TLS for Encrypted Connections

SSL/TLS will encrypt the traffic, securing the data between the server and the client’s browser. Proper SSL/TLS configuration will protect sensitive data and data integrity.

This section will cover SSL/TLS security certificates, strong TLS ciphers and HSTS to create a secure connection.

SSL Certificates

Getting an SSL certificate is the first step to secure your Nginx server. Let’s Encrypt is a popular choice that offers free SSL certificates so it’s available for everyone. SSL certificates from trusted authorities will encrypt the data between your server and users.

Install an SSL certificate using Let’s Encrypt by running the following:

sudo certbot --nginx

This is to create a secure connection and protect sensitive data. Restart Nginx to apply the changes.

Enable Strong TLS Ciphers

Enabling strong SSL/TLS ciphers is important to avoid vulnerabilities that can compromise your server’s security. Nginx has many cryptographic ciphers by default but specifying the secure ones will prevent the weak ones. Remove TLS 1.0 and TLS 1.1 from your server configuration to increase security. Leaving the server in its default configuration can lead to security risks especially with outdated TLS protocols so it’s better to update these settings to protect against attacks.

The ‘ssl_prefer_server_ciphers’ directive will use the server’s preferred ciphers to secure the TLS connection.

In your Nginx configuration, set strong ciphers and disable outdated protocols by adding this to your nginx.conf:

ssl_protocols TLSv1.2 TLSv1.3;

ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

ssl_prefer_server_ciphers on;

Restart Nginx to apply the changes.

Force HTTPS with HSTS

HTTP Strict Transport Security (HSTS) is a security policy that compels browsers to exclusively use HTTPS. By adding the Strict-Transport-Security header, all traffic will be encrypted, thereby preventing man-in-the-middle attacks.

To enforce HTTPS, add the following to your Nginx configuration:

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;

Restart Nginx to apply the changes.

Once HSTS is declared, browsers will refuse any HTTP connections so your server will be more secure.

Restrict Access to Sensitive Areas

Access to sensitive areas of your Nginx server should be controlled. IP whitelisting and password protection will add another layer of defense against unauthorized access.

Combining these will restrict access to critical server parts and protect sensitive data from attacks.

Whitelist IP Addresses

IP whitelisting is a good security measure that limits access to specific areas of your server by allowing only specific IP addresses. Configure this in your Nginx server block by specifying the allowed IP ranges and deny all others.

Use IP whitelisting by adding this to your server block:

allow 192.168.1.1;

deny all;

This will add security by only allowing trusted IPs to access sensitive areas. Restart/reload Nginx to apply the changes.

Password Protect Directories

Password protecting directories will add another layer of security by requiring users to provide credentials before accessing certain files. Create a password file and configure the auth_basic directive in Nginx to protect specific locations.

Create a password file with htpasswd and protect directories using:

location /admin/ {

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

}

This will only allow authorized users to access restricted directories. Restart Nginx to apply the changes.

Tweak your HTTP Security Headers

HTTP security headers are important to protect your web server from various attacks. Configuring headers like X-Frame-Options, Content Security Policy (CSP) and X-XSS-Protection will reduce vulnerabilities and increase Nginx server security. These headers will mitigate clickjacking and cross-site scripting (XSS) threats and provide a more secure browsing experience for users.

X-Frame-Options Header

The X-Frame-Options header will prevent clickjacking attacks by controlling how your site can be framed. Set this header to ‘DENY’ or ‘SAMEORIGIN’ to block your site from being framed from other domains so your site will be more secure.

Add this to your Nginx configuration to prevent clickjacking:

add_header X-Frame-Options "DENY";

This is a simple but effective site protection for Nginx server security.

Content Security Policy (CSP)

Content Security Policy (CSP) is a powerful tool to mitigate XSS and data injection attacks. By defining the trusted sources for content loading, CSP will prevent unauthorized script execution and reduce the risk of XSS attacks.

Use the add_header directive in Nginx to specify the permitted sources, implement CSP like this:

add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://trusted.cdn.com;";

Restart your Nginx server to apply the changes.

X-XSS-Protection Header

The X-XSS-Protection header will activate the built-in XSS filter in browsers to protect against reflected XSS attacks. Set this header to ‘1; mode=block’ so the page will not load if XSS attack is detected, add another layer of security.

Enable XSS protection with:

add_header X-XSS-Protection "1; mode=block";

This will protect users from malicious scripts.

Disable Version Information Disclosure

Revealing your Nginx version will be a big security risk as it will give attackers information about your server that can be exploited. Disabling version information disclosure (also known as the HTTP server signature) is important to minimize this risk. The server_tokens directive in your Nginx configuration file controls if the version number will be displayed in the Nginx headers. Also managing the Server header in nginx configurations is important to prevent information disclosure.

Set:

server_tokens off;

in your Nginx configuration file and restart Nginx.  This will prevent Nginx from showing its version so attackers will have a harder time to find vulnerabilities.

Monitor Nginx Access and Error Logs

Monitoring Nginx logs is important to know the requests and identify the attack attempts. Nginx access logs will record the client requests while error logs will capture the errors so you can get valuable insights of the server activity. Regular log review will keep your server secure and performant.

Log Files

Access and error logs are important to monitor your Nginx server. Nginx allows you to have separate logs for access and error messages which can be customized in the configuration file using access_log and error_log directives.

Well configured logs will track server performance and security incidents. Also disabling Nginx’s version number on automatically generated error pages is important to prevent security vulnerabilities.

Set up access and error logs with:

access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log warn;

Restart Nginx after that.

Automated Log Analysis

Automated log analysis tools like Fail2Ban will help security by identifying and responding to potential threats based on log data. Automating this will detect suspicious activity and security incidents faster.

Automating log analysis will keep your server secure.

Use a Web Application Firewall (WAF)

Adding Web Application Firewall (WAF) in your Nginx server will add another layer of security. Open-source WAFs like ModSecurity and Naxsi will protect against common attacks like XSS and SQL injection. These WAFs will monitor evasion techniques and mask sensitive data, will make your server more secure.

Limit Buffer Sizes to Prevent DoS Attacks

Setting buffer size limits in your Nginx configuration is important to prevent DoS attacks. Directives like client_body_buffer_size, client_header_buffer_size and client_max_body_size will control the size of the client request and reduce the risk of buffer overflow attacks.

Add the following to prevent buffer overflow:

client_body_buffer_size 16K;
client_header_buffer_size 1k;
client_max_body_size 8M;

Restart Nginx after that. These will make your server more resistant to DoS attacks.

Disable Unnecessary HTTP Methods

Disabling unnecessary HTTP methods is good way to secure your server. Safe methods like GET, HEAD and POST should be allowed, while unsafe methods like TRACE and DELETE should be disabled.

Edit your nginx.conf to allow only these methods will reduce the attack surface.

if ($request_method !~ ^(GET|HEAD|POST)$ ) {

return 444;

}

Restart Nginx to apply the changes.

Use Custom Diffie-Hellman Parameters

Custom Diffie-Hellman parameters will improve TLS connection security with Perfect Forward Secrecy. Generate these parameters with 2048 bits will mitigate Logjam attack vulnerabilities.

Put these in your Nginx configuration will add more security against future attacks.

Generate custom DH parameters:

openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048

And configure Nginx to use it:

ssl_dhparam /etc/ssl/certs/dhparam.pem;

Restart Nginx to apply the changes.

Nginx Configuration File Security

Nginx configuration file, typically named nginx.conf, is one of the most critical component of the web server’s security. The conf file contains settings that control the behavior of the web server, including security related configurations. To secure your Nginx web server, you must configure the nginx.conf file properly.

Here are some tips to secure your Nginx configuration file:

  • Disable unused Nginx modules to limit attack surface.
  • Configure access control to restrict access to sensitive part of your website.
  • Set security headers to tell browsers how to behave.
  • Disable server tokens to prevent information disclosure.
  • Configure error logs to monitor and analyze errors.
  • Use X-Frame-Options to prevent clickjacking attacks.

By following these you will secure your Nginx configuration file and protect your web server from threats and attacks.

Perform a Security Check with Security Tools

Use security tools to identify common misconfigurations in your Nginx setup:

ProtocolGuard’s Website Misconfiguration Scanner: run a quick test to identify protocol misconfigurations, including HTTP (with Nginx support). It helps detect issues and provides quick tips on how to fix them in your server setup.

Nginx Server Security Test with ProtocolGuard
Nginx Server Security Test with ProtocolGuard

Gixy: run your configuration through Gixy after setup to add security by detecting vulnerabilities that can be exploited by attackers. Use these tools regularly to maintain server security.

 

Related Questions

How often I should update my Nginx server?

You should check and update your Nginx server regularly to keep it secure and performant. Update your server to protect yourself from vulnerabilities.

Why disable unused Nginx modules?

Disabling unused Nginx modules will secure your server by reducing attack surface and make your server more performant with less configuration.

How to add SSL certificates in Nginx server?

How to add SSL certificates in Nginx server? Get them from trusted authority like Let’s Encrypt and configure your Nginx to use these certificates for encrypted connections.

Why custom Diffie-Hellman parameters?

Custom Diffie-Hellman parameters will greatly improve TLS security by enabling Perfect Forward Secrecy and protect against Logjam attack. Your communication will be private and secure over time.

How to monitor Nginx server for security breaches?

How to monitor Nginx server for security breaches? Review access and error logs frequently to detect threats and use automated tools like Fail2Ban to respond to suspicious activities. This will add security to your server.

Conclusion

Ensuring the security of your Nginx server is not just a one-time setup but an ongoing process. By consistently updating your server, disabling unnecessary modules, configuring SSL/TLS, implementing security headers, and monitoring logs, you can maintain a robust defense against potential threats.

Remember, a secure server is the backbone of a reliable web application, and taking these steps will help protect your data and your users.

Scroll to Top