SoFunction
Updated on 2025-04-12

Nginx production environment security configuration reinforcement implementation

The following is a comprehensive solution for Nginx production environment security configuration reinforcement, which is compiled in combination with multiple technical practices and industry standards:

1. Basic safety protection

1‌. Hide version information‌

  • existhttporserverBlock Addserver_tokens off;, avoid exposing the Nginx version number‌.
  • useheaders-more-nginx-moduleModule completely removes the response headerServer: nginxIdentification‌.

‌2. Access control and permission restrictions

  • useallow/denyInstructions limit the IP access range of sensitive interfaces‌.
  • passworker_processesandworker_connectionsConfigure the number of concurrent connections reasonably.
  • Run the Nginx process as a non-root user and specify a low-privileged account through the user directive.

3‌. SSL/TLS reinforcement

  • Enable TLS 1.3 protocol and disable unsafe protocols such as SSLv2/SSLv3‌.
  • Configure strong encryption suites, for example:
ssl_ciphers EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH;
ssl_prefer_server_ciphers on;
  • Force HTTP to jump HTTPS and enable HSTS header‌.

2. Request and resource protection

1‌. Request restrictions and anti-DDoS‌

  • set uplimit_conn_zoneLimit the number of concurrent connections for a single IP.limit_req_zoneLimit request rate‌.
  • Configure timeout parameters:
client_body_timeout 10s;
client_header_timeout 10s;
keepalive_timeout 5s;
  • DisabledTRACEmethod:limit_except GET POST { deny all; }‌
  • Directory and file protection‌
  • Disable automatic directory indexing:autoindex off;‌
  • Restrict sensitive file access:
location ~* \.(conf|log|bak)$ { deny all; }

3. Advanced security policies

‌1. Safety head enhancement

  • Add the following response headers to defend against XSS/click hijacking and other attacks:
add_header X-Content-Type-Options "nosniff";
add_header X-Frame-Options "SAMEORIGIN";
add_header Content-Security-Policy "default-src 'self'";
  • Enable browser XSS filtering using X-XSS-Protection‌.

2‌. Module and log management‌

  • Disable unused modules (such as autoindex) to reduce the attack surface‌.
  • Enable access logs and error logs, and configure log_format to record key fields (such as client IP, request time).

IV. Operation and maintenance specifications

‌1. Configuration and vulnerability management‌

  • After testing configuration using nginx -t, hot loading via nginx -s reload‌.
  • Regularly check the compilation parameters through nginx -V to ensure that no high-risk modules are included.
  • System-level protection‌
  • In combination with firewall restrictions, only necessary ports are opened (such as 80/443).
  • Set configuration file permissions through chmod (such as set to 640).

The above configuration needs to be adjusted in combination with business scenarios. It is recommended to use nginx -t verification syntax and implement it in stages. Check for known vulnerabilities regularly through vulnerability scanning tools such as CVE databases.

V. Nginx production environment standard configuration solution

1. Core parameter configuration

1‌. Process and connection control‌

worker_processes auto;  # Automatically match the number of CPU cores ‌:ml-citation{ref="1,3" data="citationList"}worker_cpu_affinity auto;  # CPU affinity optimization (Nginx 1.9+ required)‌:ml-citation{ref="1,3" data="citationList"}worker_rlimit_nofile 65535;  # Maximum number of file handles in the process ‌:ml-citation{ref="3,4" data="citationList"}events {  
    use epoll;  # High-performance I/O model (Linux environment)‌:ml-citation{ref="1,3" data="citationList"}    worker_connections 65535;  # Maximum number of concurrent connections for a single process ‌:ml-citation{ref="1,3" data="citationList"}    multi_accept on;  # Allow new connections to be accepted at the same time ‌:ml-citation{ref="3,4" data="citationList"}}

‌2. Basic HTTP parameters‌

http {  
    client_max_body_size 20m;  # File upload size limit ‌:ml-citation{ref="4" data="citationList"}    client_header_buffer_size 4k;  # Request header buffer ‌:ml-citation{ref="1,3" data="citationList"}    keepalive_timeout 65s;  # Long connection timeout ‌:ml-citation{ref="2,4" data="citationList"}    sendfile on;  # Enable efficient transmission mode ‌:ml-citation{ref="3,4" data="citationList"}    tcp_nopush on;  # Reduce the number of network messages ‌:ml-citation{ref="3,4" data="citationList"}}

2. Safety configuration specifications

1‌. Information Hide and Access Control‌

server_tokens off;  # Hide Nginx version number ‌:ml-citation{ref="1,2" data="citationList"}add_header Server "Custom";  # Custom Server header (need to headers-more module)‌:ml-citation{ref="4,8" data="citationList"}
location /nginx_status {  
    allow 192.168.1.0/24;  # Restrict status interface IP access ‌:ml-citation{ref="5,6" data="citationList"}    deny all;  
}

2‌. SSL/TLS optimization‌

ssl_protocols TLSv1.2 TLSv1.3;  # Disable the old protocol ‌:ml-citation{ref="1,3" data="citationList"}ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;  
ssl_prefer_server_ciphers on;  # Priority server encryption suite ‌:ml-citation{ref="1,3" data="citationList"}ssl_session_cache shared:SSL:10m;  # Session cache reuse ‌:ml-citation{ref="3,4" data="citationList"}

3. Performance optimization strategy

‌1. Resource Caching and Compression‌

gzip on;  # Enable GZIP compression ‌:ml-citation{ref="2,4" data="citationList"}gzip_min_length 1k;  # Minimum compressed file size ‌:ml-citation{ref="2,4" data="citationList"}open_file_cache max=1000 inactive=20s;  # File metadata cache ‌:ml-citation{ref="3,4" data="citationList"}
proxy_cache_path /data/cache levels=1:2 keys_zone=mycache:10m;  # Reverse proxy cache ‌:ml-citation{ref="4" data="citationList"}

‌2. Load balancing configuration‌

upstream backend {  
    server 10.0.0.1:80 weight=5;  # Weight allocation ‌:ml-citation{ref="3,4" data="citationList"}    server 10.0.0.2:80 backup;  # Alternate Node ‌:ml-citation{ref="3,4" data="citationList"}    keepalive 32;  # Long connection multiplexing ‌:ml-citation{ref="4" data="citationList"}    check interval=3000 rise=2 fall=3 timeout=1000;  # Health check (need nginx_upstream_check module)‌:ml-citation{ref="6" data="citationList"}}

4. Operation and maintenance management standards

‌1. Logs and monitoring

log_format main '$remote_addr - $request_time - "$request" $status';  # Custom log format ‌:ml-citation{ref="2,3" data="citationList"}access_log /var/log/nginx/ main buffer=32k flush=5m;  # Buffer write to log ‌:ml-citation{ref="4" data="citationList"}error_log /var/log/nginx/ warn;  # Error log level control ‌:ml-citation{ref="3,4" data="citationList"}

‌2. System-level reinforcement

  • Configuration file permissions: chmod 640 /etc/nginx/ ‌
  • Run as a non-privileged user: user www-data; ‌
  • Firewall restrictions: Only open port 80/443 ‌

Implementation Instructions‌

  • After the configuration update, nginx -t test syntax must be executed ‌
  • It is recommended to use logrotate to achieve automatic log cutting ‌
  • OpenResty enhancements (such as dynamic WAF) are recommended in production environments‌

6. Configuration example:

Standard configuration

worker_processes auto;
 
events {
    worker_connections 1024;
}
 
http {
    include       ;
    default_type  application/octet-stream;
 
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
 
    access_log  /var/log/nginx/  main;
    error_log   /var/log/nginx/ warn;
 
    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;
    keepalive_timeout  65;
    types_hash_max_size 2048;
 
    server {
        listen       80;
        server_name  localhost;
 
        location / {
            root   /usr/share/nginx/html;
            index   ;
        }
 
        error_page   500 502 503 504  /;
        location = / {
            root   /usr/share/nginx/html;
        }
    }
}

Production environment optimization suggestions:

  • Increase the number of concurrent connections: Adjust worker_connections according to the actual load. For example, if the server has a 16-core CPU, it can be set to 16384 or higher.
  • Enable Gzip compression: Reduce the amount of data transmitted and improve page loading speed.
  • Configure HTTPS: Enhanced security and use TLS protocol.
  • Use efficient log format: For example, logs in json format are used for subsequent analysis.
  • Configure cache: Use Nginx's proxy_cache or fastcgi_cache to cache static files and dynamic content.
  • Load balancing: Distribute requests between multiple servers, using Nginx's upstream module.
  • Security enhancement: Configure HTTP headers to enhance security, such as X-Frame-Options, Content-Security-Policy, etc.
  • Monitoring and alarm: Set up monitoring and alarm mechanisms to discover and solve problems in a timely manner.
  • Performance Tuning: Adjust parameters such as keepalive_timeout, client_max_body_size to adapt to high concurrency scenarios.
  • Use efficient third-party modules: For example, ngx_pagespeed, ngx_brotli, etc.

Optimized configuration example:

worker_processes auto; # Automatically set the number of work processes based on the number of CPU cores, usually set to the number of CPU cores or 2 times the number of CPU cores.pid        /var/run/; # Set the nginx process ID file path.worker_rlimit_nofile 16384; # Set the maximum number of file descriptors that a single worker can open.events {
    worker_connections 16384; # Adjust the number of concurrent connections according to the actual load.    multi_accept on; # Allows each worker to accept multiple new connections at the same time.}
http {
    ... # Other configurations remain the same.    gzip on; # Enable Gzip compression.    gzip_types text/plain application/xml text/css application/javascript application/json application/x-javascript text/xml application/xml+rss text/javascript; # Set the MIME type that needs to be compressed.    ... # Other configurations remain the same.    server {
        listen       80 default_server; # Listen to port 80 and set as the default server.        listen       443 ssl default_server; # Listen to port 443, enable SSL encryption, and set it as the default server.        server_name  localhost; # Set according to the actual domain name.        ssl_certificate       /etc/ssl/certs/; # SSL certificate path.        ssl_certificate_key   /etc/ssl/private/; # SSL private key path.        ssl_session_cache    shared:SSL:1m; # Set SSL session cache.        ssl_session_timeout  5m; # Set the SSL session timeout time.        ... # Other configurations remain the same.        location / { ... } # Other location configurations remain unchanged.        ... # Other configurations remain the same.    }

This is the end of this article about the implementation of Nginx production environment security configuration reinforcement. For more information about Nginx production environment security reinforcement, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!