Nginx Common Configurations
Reverse Proxy
HTTP
http { |
- Response static files: {root path}/requestURI
- Proxy requests: {proxy_pass path}/requestURI
Passing Request Headers
By default, NGINX redefines two header fields in proxied requests, “Host” and “Connection”, and eliminates the header fields whose values are empty strings. “Host” is set to the $proxy_host
variable, and “Connection” is set to close
.
HTTPS
http { |
HTTP to HTTPS
http { |
Optimization
Caching
Cache static files
When you build static assets with versioning/hashing mechanisms, adding a version/hash to the filename (cache-busting filenames) or query string is a good way to manage caching. In such a case, you can add a long max-age
value and immutable
because the content will never change.
http { |
http { |
After setting cache, the following headers will be present in the response headers:
Cache-Control: max-age=604800, public, must-revalidate, proxy-revalidate |
Warning: Cache-Control "public, immutable"
for JS, CSS may cause program exceptions after update program.
Compression
Enable gzip
http { |
After enable gzip, the following headers will be present in the response headers:
content-encoding: gzip |
Enable HTTP/2
The ngx_http_v2_module
module (1.9.5) provides support for HTTP/2. This module is not built by default, it should be enabled with the --with-http_v2_module
configuration parameter.
To enable HTTP/2, you must first enable SSL/TLS on your website. HTTP/2 requires the use of SSL/TLS encryption, which provides a secure connection between the web server and the client’s browser.
http { |
Connection Handling
Keepalive Connections
http { |
Keepalive connections reduce the overhead of repeatedly establishing new connections for multiple requests from the same client (e.g., a web browser loading multiple assets from a single page). This saves time and resources associated with TCP handshake and SSL/TLS negotiation.
TCP Optimizations
http { |
- sendfile → efficient file transfer.
- tcp_nopush → optimizes packet sending.
- tcp_nodelay → reduces latency for small packets.
When sendfile on;
and tcp_nopush on;
are used together in Nginx for serving static files, Nginx will initially buffer data to send full TCP packets.
However, for the very last packet(s) of a file, which may not be full, Nginx will dynamically disable tcp_nopelay
(effectively removing TCP_CORK
) and enable tcp_nodelay
to ensure that these remaining partial packets are sent immediately without delay, thus completing the file transfer quickly.
SSL/TLS Optimization
http { |
ssl_session_cache
andssl_session_timeout
: Reuse SSL sessions → fewer handshakes.ssl_protocols
: TLS 1.3 is faster than TLS 1.2.
Worker Processes and Connections
http { |
worker_processes
: This directive determines the number of Nginx worker processes that will handle incoming requests. A common practice is to set this toauto
, which automatically sets the number of worker processes to match the number of CPU cores on your server. This ensures that each core is utilized efficiently.
Logging
Disabling Access Logs
While access logs are valuable for monitoring and debugging, they can consume significant CPU and disk resources on high-traffic sites. If you don’t need detailed logging for every request, you can either buffer the logs or disable them entirely to reduce overhead.
To disable access log for static files
http { |
Or disable all access logs
http { |
Buffering Logs (Optional)
Instead of writing to the log file for every single request, you can configure Nginx to buffer log data and write it in larger chunks. This reduces the number of disk I/O operations and can improve performance.
Benefits of Log Buffering:
- Reduced I/O Operations: Fewer, larger writes to disk instead of many small writes, improving performance.
- Lower CPU Consumption: Less overhead associated with managing individual log entries.
- Improved Disk Lifespan: Reduced wear and tear on storage devices.
Considerations:
- Data Latency: Buffered log entries are not immediately written to disk, which can introduce a slight delay in log availability for real-time analysis.
- Memory Usage: Buffering consumes a small amount of memory per worker process.
- Out-of-Order Entries: In rare cases, if multiple worker processes are writing to the same log file with buffering enabled, log entries might appear slightly out of order if not flushed simultaneously. However, most log analysis systems can handle this by sorting based on timestamps.
Settings
Timeout
http { |
Upload File Size
http { |
Enable CORS for API
Enable CORS for specified sites
http { |
Enable CORS for all sites
http { |
Load Balancing
http { |
Test the Nginx Configuration is Updated
Adding the following config to the Nginx configuration file. You can verify if the configuration is updated by updating the return status code (e.g. 403 Forbidden, 406 Not Acceptable, 423 Locked) of the /test
location and visiting the test URL http://yourDomain/testConfig.
location /testConfig { |
Appendixes
Embedded Variables
$proxy_host
: name and port of a proxied server as specified in the proxy_pass directive;$proxy_add_x_forwarded_for
: the “X-Forwarded-For” client request header field with the$remote_addr
variable appended to it, separated by a comma. If the “X-Forwarded-For” field is not present in the client request header, the$proxy_add_x_forwarded_for
variable is equal to the $remote_addr variable.$host
: In this order of precedence: host name from the request line, or host name from the “Host” request header field, or the server name matching a request.$remote_addr
: Client address
Build Nginx From Source
# Download Nginx source code |
You can know the latest version of Nginx by visiting the Nginx download page.
tar -zxvf nginx-{latest-stable-version}.tar.gz |
Common errors when running ./configure
1. ./configure: error: the HTTP rewrite module requires the PCRE library.
Solution
sudo apt update && apt upgrade -y && apt autoremove && apt autoclean |
2. ./configure: error: the HTTP image filter module requires the GD library. You can either do not enable the module or install the libraries.
Solution
sudo apt update && apt upgrade -y && apt autoremove && apt autoclean |
3. ./configure: error: C compiler cc is not found
Solution
sudo apt update && apt upgrade -y && apt autoremove && apt autoclean |
Successful output of configure
Configuration summary |
You can add the following parameters to specify paths:
--prefix=/var/www/html \ |
# Build nginx |
Successful output of build
make -f objs/Makefile install |
# Start nginx |
Rebuild Nginx source
# Just remove the nginx binary file. Or completely remove nginx `sudo apt-get purge nginx` or `yum remove package` |
References
[1] Configuring HTTPS servers - Nginx
[2] Alphabetical index of variables - Nginx