DeveloperBreeze

Nginx is a powerful and widely used web server that can handle a variety of tasks such as reverse proxying, load balancing, caching, and serving static content. While Nginx is known for its speed and reliability, securing it should be a top priority for every system administrator. By default, Nginx is quite secure, but with additional configurations and security practices, you can significantly harden your web server and protect your data. This guide covers the top 25 best security practices for securing your Nginx web server.


1. Update Nginx Regularly

Keeping your Nginx version updated is crucial to staying protected against known vulnerabilities. Regularly check for updates and apply patches as soon as they are released.

sudo apt update && sudo apt upgrade nginx

2. Disable Unused Nginx Modules

By default, Nginx comes with multiple modules, some of which may not be necessary for your use case. Disable any modules that aren’t needed to reduce the attack surface.

3. Run Nginx as a Non-Root User

By default, Nginx runs as the root user. Change this to a non-privileged user like www-data to limit the scope of potential security breaches.

In your Nginx configuration file, set:

user www-data;

4. Use SSL/TLS Certificates

One of the most important steps in securing Nginx is enabling SSL/TLS. This ensures that all communication between clients and the server is encrypted. You can use Let's Encrypt for free SSL certificates.

sudo certbot --nginx -d yourdomain.com

5. Disable SSL/TLS Protocols Below Version 1.2

Older SSL protocols (such as SSLv3 and TLSv1.0) are insecure. To mitigate vulnerabilities like the POODLE attack, disable these protocols and only use TLSv1.2 and above.

ssl_protocols TLSv1.2 TLSv1.3;

6. Enforce Strong Cipher Suites

Use secure SSL/TLS cipher suites to protect against attacks like BEAST, CRIME, and BREACH. Define strong ciphers in your configuration:

ssl_ciphers HIGH:!aNULL:!MD5;

7. Use HTTP Strict Transport Security (HSTS)

HSTS tells browsers to only communicate with your server using HTTPS. It can help prevent man-in-the-middle attacks.

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

8. Limit Request Size

Prevent large payloads from overwhelming your server by setting a limit on the size of client requests.

client_max_body_size 1M;

9. Hide Nginx Version Information

Displaying your Nginx version publicly can expose your server to attackers looking for specific vulnerabilities. Hide the version in responses:

server_tokens off;

10. Set Up Fail2Ban for Nginx

Fail2Ban is a tool that helps protect Nginx from brute-force and DoS attacks by blocking IP addresses after a series of failed attempts. Install Fail2Ban and configure it for Nginx.

sudo apt install fail2ban

Then, create a configuration for Nginx:

/etc/fail2ban/jail.local

11. Limit HTTP Methods

Most websites only need GET and POST requests. Restrict other HTTP methods like PUT, DELETE, or TRACE to reduce potential attack vectors.

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

12. Enable HTTP Headers for Security

Use additional HTTP headers to protect your website from common vulnerabilities like XSS and Clickjacking.

add_header X-Frame-Options "DENY";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";

13. Disable Directory Listing

Disable directory listing to prevent attackers from viewing the contents of your server directories.

autoindex off;

14. Disable Buffering for Proxy Requests

Disabling buffering for proxy requests can reduce the risk of memory-based attacks.

proxy_buffering off;

15. Limit Connection Requests

Use the limit_req module to throttle the rate of requests from clients, reducing the risk of DoS attacks.

limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
limit_req zone=one burst=5;

16. Implement IP Address Whitelisting

Limit access to sensitive areas like admin panels by allowing only specific IP addresses.

location /admin {
    allow 192.168.1.1;
    deny all;
}

17. Use a Web Application Firewall (WAF)

A WAF like ModSecurity can block common web attacks, such as SQL injection and XSS.

Install ModSecurity and integrate it with Nginx to filter and block malicious traffic.

18. Isolate Virtual Hosts

If you're hosting multiple domains or applications on a single server, isolate each virtual host to prevent a compromise on one affecting others.

Each site should have its own Nginx configuration file, user, and directory.

19. Use DDoS Mitigation Tools

To prevent Distributed Denial of Service (DDoS) attacks, use tools like DDoS mitigation services, cloud-based solutions, or rate limiting mechanisms provided by Nginx.

20. Protect Against Slowloris Attacks

To mitigate Slowloris attacks, which open connections and send data very slowly, configure client_body_timeout and client_header_timeout.

client_body_timeout 10s;
client_header_timeout 10s;

21. Log Suspicious Requests

Enable logging of malicious or suspicious requests, including the IP address and user agent, for forensic analysis.

log_format suspicious '$remote_addr - $remote_user [$time_local] "$request" ';
error_log /var/log/nginx/error.log;

22. Monitor Logs for Intrusions

Regularly monitor Nginx logs for potential attacks or unusual traffic patterns. Tools like GoAccess or ELK Stack can help visualize and analyze logs in real-time.

23. Limit Simultaneous Connections

Limit the number of simultaneous connections from a single IP address to avoid overload or abuse:

limit_conn_zone $binary_remote_addr zone=addr:10m;
limit_conn addr 5;

24. Prevent Clickjacking

Use the X-Frame-Options header to prevent your website from being embedded in an iframe, reducing the risk of clickjacking attacks.

add_header X-Frame-Options "DENY";

25. Disable Unnecessary MIME Types

Remove or block the execution of unwanted file types like .php or .exe if not needed on your server.

location ~* \.(exe|sh|bat)$ {
    return 403;
}

Conclusion

Securing an Nginx web server involves multiple layers of defense, from using encryption and SSL/TLS to configuring access control and monitoring traffic. Implementing these 25 best security practices will significantly improve the security posture of your Nginx server, helping to protect your web applications and sensitive data from attacks. Regularly auditing your security settings and staying updated with the latest security patches is equally important for maintaining a robust defense against evolving threats.

By following these steps, you can harden your Nginx web server and make it more resilient to common and sophisticated cyberattacks.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial

🛡️ Protect Your Forms Like a Pro: Anti-Spam Techniques That Actually Work

Before we dive in, it's important to know: most spammers use scripts, not humans. These bots scan for forms, autofill fields, and send POST requests rapidly—sometimes thousands per hour.

So your goal isn’t to annoy humans, it’s to trip up bots.

Apr 04, 2025
Read More
Tutorial
javascript

Variables and Constants

     {
       let x = 10;
       console.log(x); // 10
     }
     console.log(x); // Error: x is not defined
  • Variables are accessible within the entire function they are declared in.
  • Example:

Dec 10, 2024
Read More
Tutorial
php

Laravel Best Practices for Sharing Data Between Views and Controllers

  • Use service providers for application-wide data.
  • Use middleware for context-sensitive or user-specific data.
  • Don’t duplicate logic in multiple controllers or views.
  • Share common data globally using View::share.

Nov 16, 2024
Read More
Tutorial
bash

How to Install and Configure Apache on Ubuntu

Then, enable the firewall (if not already enabled):

sudo ufw enable

Oct 21, 2024
Read More
Tutorial
bash

How to Create SSL for a Website on Ubuntu

Run the following command to obtain the certificate and automatically configure your Nginx server:

sudo certbot --nginx

Oct 21, 2024
Read More
Tutorial
python

Enhancing Productivity with Custom Keyboard Shortcuts in Your IDE

  • Windows/Linux: Ctrl + Alt + S to open settings, then navigate to Keymap.
  • Mac: Cmd + , to open settings, then navigate to Keymap.

For example, to create a custom shortcut for running all tests, search for "Run All Tests" and assign a new shortcut like Ctrl + Shift + R.

Aug 20, 2024
Read More
Tutorial
bash

Building a Secure SSH Configuration for Remote Access

Edit the SSH configuration file and set PasswordAuthentication to no:

   PasswordAuthentication no

Aug 19, 2024
Read More
Tutorial
bash

Securing Your Linux Server: Best Practices and Tools

     sudo ufw status

For more granular control, use iptables to manage your server's firewall rules. iptables allows you to define rules that control incoming and outgoing traffic.

Aug 19, 2024
Read More
Tutorial
json bash

Building Progressive Web Apps (PWAs) with Modern APIs

{
  "name": "My Progressive Web App",
  "short_name": "MyPWA",
  "start_url": "/index.html",
  "display": "standalone",
  "background_color": "#ffffff",
  "theme_color": "#4a90e2",
  "icons": [
    {
      "src": "images/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "images/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ]
}

Ensure you have the icon images in the specified sizes in the images directory.

Aug 05, 2024
Read More
Tutorial
python bash

Deploying a Flask Application on a VPS Using Gunicorn and Nginx

gunicorn --bind 0.0.0.0:8000 app:app

Replace app:app with your actual Flask application entry point.

Aug 03, 2024
Read More
Code
php

Get Current URL

No preview available for this content.

Jan 26, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!