Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Nginx Hardening & Performance Tips

· 4 min read · Home Security

In this article
  1. Why Nginx Security and Performance Matter
  2. Core Security Hardening Steps
  3. Performance Tuning: Worker Processes and Connections
  4. Caching and Compression for Speed
  5. Common Mistakes to Avoid
  6. Comparing Nginx with Other Servers
  7. Costs and Effort
  8. Safety and Best Practices
  9. Frequently Asked Questions

To harden and speed up an Nginx web server, you need to configure security headers, restrict access, tune worker processes, and enable caching and compression. This article covers the most effective measures you can implement today, balancing security with performance.

Why Nginx Security and Performance Matter

Nginx is one of the most widely used web servers, powering millions of websites. Its event-driven architecture makes it efficient, but misconfiguration can leave it vulnerable to attacks or slow under load. Hardening reduces the attack surface, while performance tuning ensures your server handles traffic smoothly. Both are essential for a reliable, secure web presence.

Core Security Hardening Steps

Start with these fundamental security measures. They are easy to implement and have a high impact.

  • Hide Nginx version: Add server_tokens off; in the http block to prevent attackers from seeing the exact version.
  • Set secure headers: Add headers like X-Content-Type-Options: nosniff, X-Frame-Options: DENY, and Referrer-Policy: no-referrer. Use add_header directives.
  • Disable unnecessary modules: Compile Nginx with only the modules you need. Fewer modules mean fewer potential vulnerabilities.
  • Use strong SSL/TLS settings: Disable old protocols (SSLv2, SSLv3, TLSv1, TLSv1.1) and enable only TLSv1.2 and TLSv1.3. Set a strong ciphersuite.
  • Limit request size: Set client_max_body_size to a reasonable value (e.g., 1M) to prevent large upload attacks.
  • Implement rate limiting: Use limit_req_zone and limit_conn_zone to throttle requests per IP, mitigating brute-force and DDoS attacks.
  • Restrict access by IP: Use allow and deny directives for admin panels or sensitive locations.

Performance Tuning: Worker Processes and Connections

Nginx performance depends heavily on how you configure worker processes. The goal is to use CPU cores efficiently without overloading memory.

  • Set worker_processes: A common rule is to set it to the number of CPU cores (use auto to let Nginx detect it).
  • Set worker_connections: This defines the maximum number of simultaneous connections per worker. A typical value is 1024 or 2048, but you can increase it if your server has enough file descriptors.
  • Enable keepalive: Set keepalive_timeout to a reasonable value (e.g., 65 seconds) and keepalive_requests to 100 or more. This reduces TCP handshake overhead.
  • Use event-driven I/O: The default epoll event model on Linux is efficient. Ensure it is enabled.

Caching and Compression for Speed

Caching and compression are the quickest wins for performance. They reduce bandwidth and server load.

  • Enable gzip compression: Add gzip on; and specify gzip_types for text, CSS, JavaScript, and JSON. This can reduce transfer size by up to 70%.
  • Set up caching: Use proxy_cache_path and proxy_cache directives if Nginx is used as a reverse proxy. For static files, set expires headers to leverage browser caching.
  • Use open_file_cache: This caches file descriptors and metadata, speeding up static file serving. Configure open_file_cache max=1000 inactive=20s; and related directives.

Common Mistakes to Avoid

Even experienced administrators make these errors. Avoiding them will save you from security and performance issues.

  • Leaving default error pages: They reveal server info. Customize them to show minimal details.
  • Not testing configuration: Always run nginx -t after changes to catch syntax errors before reloading.
  • Overusing redirects: Too many redirects slow down user experience and waste server resources. Keep them minimal.
  • Ignoring logs: Regularly review error and access logs to spot anomalies or performance bottlenecks.

Comparing Nginx with Other Servers

Nginx is often compared to Apache. Nginx uses an asynchronous, event-driven architecture, while Apache uses a process-based model. This makes Nginx more efficient under high concurrent loads, especially for static files. Apache offers more flexibility with per-directory configuration via .htaccess, but that comes at a performance cost. For most modern web applications, Nginx is the preferred choice as a reverse proxy and static file server.

Costs and Effort

Nginx is open-source and free to use. The main cost is the time to learn and configure it properly. For advanced features like load balancing and caching, you can use the open-source version. Nginx Plus (commercial) offers additional features like active health checks and session persistence, but it is not required for basic hardening and performance tuning. The effort is moderate: a few hours of configuration and testing will cover most needs.

Safety and Best Practices

Before making changes, always back up your configuration files. Use a staging environment to test. After applying changes, reload Nginx gracefully with nginx -s reload to avoid downtime. Monitor your server's resource usage to ensure your tuning is effective. Keep Nginx updated to the latest stable version to receive security patches.

Frequently Asked Questions

How do I hide the Nginx version?

Add server_tokens off; in the http block. This removes the version number from error pages and the Server header.

What is the best worker_processes value?

Set it to auto or the number of CPU cores. You can check cores with nproc. Too many workers waste memory, too few underutilize CPU.

How can I test my Nginx configuration?

Run nginx -t to check syntax. It will tell you if the configuration is valid. Always do this before reloading.

Is gzip compression safe?

Yes, but be cautious with the BREACH attack. Disable compression for responses that contain sensitive data, like CSRF tokens. Use gzip_disable "msie6" for old browsers.

Should I use HTTP/2 or HTTP/3?

HTTP/2 is widely supported and easy to enable with listen 443 ssl http2;. HTTP/3 (QUIC) is newer and offers better performance over UDP, but requires more configuration and is not yet universal. Start with HTTP/2.

How do I set up basic rate limiting?

Define a zone: limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s; then apply it: limit_req zone=mylimit burst=20 nodelay; in the location block you want to protect.