Have you ever used Nginx to optimize performance? Or should I use the software directly after it is installed?
Today, the editor will share with you some common Nginx optimized configurations.
Overall, Nginx optimization can be performed from multiple levels:
- System level
- Configuration level
- Cache utilization
- Compression strategy
- Load balancing strategy
Next, let’s take a look at how to do it.
1 Nginx configuration optimization
- Adjustment
worker_processes
Parameters, usually set to equal the number of CPU cores of the server. - Adjustment
worker_connections
Parameters to increase the number of connections that each Worker process can open.
events { worker_connections 1024; } worker_processes auto;
- Use the HTTP/2 protocol to improve page loading speed by leveraging features such as multiplexing and head compression.
server { listen 80; listen [::]:80; listen 443 ssl http2; listen [::]:443 ssl http2; }
- Optimize SSL/TLS configurations, such as turning off unsafe encryption algorithms, using TLS 1.3, etc., to improve security and performance.
ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5;
2. Cache utilization
- Enable file caching to reduce disk I/O operations.
- Use proxy cache to cache the response content of the backend server.
- Set a reasonable cache expiration strategy through
Cache-Control
andExpires
The header controls the validity period of the browser cache and reduces the number of requests.
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off; server { location / { proxy_cache my_cache; proxy_pass http://backend; } }
In the above configuration,proxy_cache_path
The instruction is used to configure a cache area that stores the response content of the proxy request. This instruction is usuallyhttp
Used in blocks and isngx_cache_purge
Modules andngx_http_proxy_module
Part of the module.
The meanings of each parameter in this configuration are as follows:
-
/data/nginx/cache
: This is the physical path to cache file storage. Nginx will store cached data in this directory. -
levels=1:2
: This defines the directory structure of the cache file. In this example,1:2
Meaning Nginx will store cache files in/data/nginx/cache
under the primary and secondary directories.1
Represents the number of first-level directories (usually 3, such asdata
、tmp
、html
),2
Represents the number of second-level directories (usually 64, based on 0 to 63 numbers or letters). -
keys_zone=my_cache:10m
: This defines a shared memory area for storing cache keys and metadata.my_cache
is the name of the region.10m
Indicates that the allocated shared memory size is 10MB. This area is used to store cached keys and related information to quickly retrieve and verify cache validity. -
max_size=10g
: This specifies the maximum size of the cache area, in bytes. In this example, the maximum size of the cache area is 10GB. When the cached data reaches this size, Nginx will use a strategy (usually the least recently used LRU algorithm) to remove the old cached data, making room for the new cached data. -
inactive=60m
: This defines how long it takes for a cache object to be considered "inactive" and may be removed after it has not been accessed. In this example, if a cache object is not accessed within 60 minutes, it will be considered inactive. This parameter helps control the life cycle of old data in the cache. -
use_temp_path=off
: This specifies whether to use a temporary path to store cached files.off
Indicates that no temporary path is used, all cache files are stored directly in the specified/data/nginx/cache
Under the path. If set toon
, then Nginx will use a temporary directory to store cached files. After the files are accessed, they will be moved to the permanent cached directory.
Three Compression Strategy
- Enable Gzip compression to reduce data transfer and improve response speed.
- Balance the compression level and minimum compression size based on the server's CPU capabilities and network conditions for optimal performance.
gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 5; gzip_min_length 256; gzip_types text/plain application/xml application/json application/javascript text/css;
The meanings of each configuration are as follows:
-
gzip on;
: Enable Gzip compression. When this command is set toon
When Nginx tries to compress the response body and send it to the client. -
gzip_vary on;
: This directive tells Nginx to add in the response headerVary: Accept-Encoding
. This allows the cache system (such as a proxy or CDN) to store different response versions depending on whether the client supports compression. -
gzip_proxied any;
: This directive allows Nginx to compress responses received from any proxy server, whether or not the response has been compressed.any
Indicates that Nginx will try to compress it again regardless of whether the original response is compressed or not. Other options includeoff
(Not compressing the response of any proxy) andexpired
(Compress only those expired proxy responses). -
gzip_comp_level 5;
: This command sets the Gzip compression level. The compression levels range from 1 (fastest, lowest compression ratio) to 9 (slowest, highest compression ratio). 5 is a common value that balances speed and compression ratio. -
gzip_min_length 256;
: This instruction sets the minimum length of the response body. Nginx will compress it only when the response body is greater than or equal to this value. Set to 256 bytes here, meaning that compression will only be performed if the response body is greater than or equal to 256 bytes. -
gzip_types text/plain application/xml application/json application/javascript text/css;
: This directive specifies which MIME types responses should be compressed. In this example, responses of text, XML, JSON, JavaScript, and CSS types will be compressed.
4. Security optimization
- Hide the Nginx version number information, and change the source code to hide the Nginx software name and version number.
- Modify the default user of the Nginx service to improve security.
- Configure OCSP stapling, ssl_stapling, ssl_stapling_verify, etc. to enhance the security of SSL/TLS.
Hiding version information can improve the security of the server, making it difficult for attackers to infer possible security vulnerabilities on the server through version information.
There are three ways to hide the Nginx version number. Generally speaking, we can just use the first method.
Modify the configuration file
In the Nginx configuration file,http
Add the following configuration to the block:
server_tokens off;
After this setting, Nginx will not display the version number on the error page.
After the configuration is complete, save the configuration file and reload Nginx to apply the changes:
nginx -t # Test whether the configuration file is correctnginx -s reload # Reload Nginx configuration
This method can hide version information on the error page, but may not completely hide version information in all response headers.
Modify the Nginx source code
If you want to modify the Nginx version information from the root, you need to recompile Nginx. The steps are as follows:
- Revise
src/core/
Version definition in the file. - Revise
src/http/ngx_http_header_filter_module.c
Server string in the file. - Revise
src/http/ngx_http_special_response.c
Information at the bottom of the error page in the file.
After modifying these files, Nginx needs to be recompiled. After compiling and installing this way, the version information of Nginx will be completely modified.
Use third-party modules
If you need to dynamically modify the version information in the response header, you can useheaders-more-nginx-module
Module. This module allows you to dynamically add, modify or delete Nginx response headers. Through this module, you can fully control itServer
The content of the response header.
Which method to choose depends on your specific needs and environment.
If you just want to simply hide version information, modifying the configuration file may be the easiest way to do it. If you need more thorough control of version information, you may want to consider modifying the source code and recompiling Nginx.
5. Monitoring and log optimization
- Use log analysis tools such as ELK Stack, Graylog, etc. to analyze and visualize Nginx's log data.
- Regular maintenance policies, such as updating Nginx, reviewing configuration files, backup configuration files, etc.
- Use timed task tools (such as cron) to clean cache periodically, using Nginx's
proxy_cache_path
Instructionsinactive
Parameters set the cache expiration time.
The log configuration is as follows:
access_log /var/log/nginx/; error_log /var/log/nginx/;
6. System-level optimization
- Adjust file descriptor limits (in
/etc/
Set in:
-max = 65535
- Resize the TCP connection queue (in
/etc/
Set in:
= 1024
7 Failover Optimization
- Optimize health checks, adjust parameters such as the frequency, timeout time, and inspection content to more accurately detect server failures.
- In combination with the monitoring system, the server's health status, request traffic, response time and other indicators are monitored in real time, and potential problems are discovered in a timely manner, and early warning and handling are carried out.
Configure health checks (using third-party modulesnginx_upstream_check_module
):
upstream backend { server check; server check; }
This is the end of this article about several methods of Nginx performance optimization. For more related content on Nginx performance optimization, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!