Custom Error Pages
The default error response pages in Nginx can be modified to serve custom content. This directive can also map specific HTTP status codes to diffferent responses. It is valid with in the http, server, location, and if in location contexts.
Directive Syntax:
error_page code ... [=[response]] uri;
error_page: The directive keyword.code: The original HTTP status code to handle.=: An optional operator to change the final response code.response: The new HTTP status code to return to the client.uri: The internal URI of the custom error page.
Example 1: Serving a Static Page for 404 Errors
server {
listen 80;
server_name site.example.com;
root /var/www/html;
error_page 404 /notfound.html;
}
Example 2: Serving a Custom Error Page from a Specific Directory
server {
listen 80;
server_name site.example.com;
root /var/www/html;
error_page 404 /custom_404.html;
location = /custom_404.html {
root /opt/error_pages;
}
}
Example 3: Changing the Response Code for a 404 Error
This configuration returns a 302 Found redirect when a 404 Not Found condition is triggered.
server {
listen 80;
server_name app.example.com;
root /var/www/html;
error_page 404 =302 /redirect_page.html;
location = /redirect_page.html {
root /opt/error_pages;
}
}
Checking File Existence with try_files
The try_files directive tests for the existence of files in a specified order and serves the first one found. If none are found, it performs an internal redirect to the final parameter, which must be a valid URI.
Directive Syntax:
try_files file ... uri;
try_files file ... =code;
- Context:
server,location
Example:
server {
listen 80;
server_name app.example.com;
root /var/www/html;
location / {
root /var/data;
try_files $uri $uri.html $uri/index.html /default/default.html;
}
}
Configuring Log File Locations
Error and access logs can be defined separately for different server blocks, allowing for organized log management.
Error Log Syntax:
error_log file [level];
error_log: Directive keyword.file: Path to the log file.level: (Optional) Logging severity (e.g.,info,debug,error).
Example: Separating Logs for Multiple Sites
# Configuration for site1.example.com
server {
listen 80;
server_name site1.example.com;
root /var/www/site1;
error_log /var/log/nginx/site1_error.log warn;
access_log /var/log/nginx/site1_access.log;
}
# Configuration for site2.example.com
server {
listen 80;
server_name site2.example.com;
root /var/www/site2;
error_log /var/log/nginx/site2_error.log warn;
access_log /var/log/nginx/site2_access.log;
}
After creating the log directory (/var/log/nginx/), test and reload the configuration:
nginx -t && nginx -s reload
Persistent (Keepalive) Connections
HTTP is built on TCP. Keepalive connections allow multiple requests and responses over a single TCP connection, improving efficiency.
Key Directives:
keepalive_timeout timeout [header_timeout];- Sets the time a keepalive connection stays open with the client. Default is 75 seconds. Settting it to
0disables keepalive.
- Sets the time a keepalive connection stays open with the client. Default is 75 seconds. Settting it to
keepalive_requests number;- Defines the maximum number of requests allowed per keepalive connection. Default is 100.
keepalive_disable none | browser ...;- Disables keepalive connections for specific browsers.
Example Configuration:
http {
keepalive_timeout 65 60;
keepalive_requests 500;
}
Configuring Nginx as a File Download Server
The ngx_http_autoindex_module generates directory listings for requests ending with a slash (/).
Common Directives:
autoindex on | off;- Enables or disables directory listing.autoindex_exact_size on | off;- Displays exact file sizes in bytes (on) or rounded sizes (off).autoindex_localtime on | off;- Uses local server time instead of GMT.autoindex_format html | xml | json | jsonp;- Sets the output format for the listing.limit_rate rate;- Limits the transfer speed to clients (bytes per second). Can also be set via the$limit_ratevariable.
Example 1: Basic Directory Listing
server {
listen 80;
server_name dl.example.com;
root /var/www/html;
location /files {
autoindex on;
alias /shared/downloads;
}
}
Example 2: Formatted Listing with Speed Limit
location /downloads {
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
autoindex_format json;
limit_rate 512k;
alias /data/media;
}
Handling Client File Uploads
Settings control the maximum size of uploads and buffer handling.
client_max_body_size size;- Limits the maximum allowed size of a client request body. Default is1m. Exceeding this causes a413error.client_body_buffer_size size;- Sets the buffer size for reading the client request body. Default is16k.client_body_temp_path path [levels];- Defines the directory for storing temporary files from large request bodies.
Example:
server {
client_max_body_size 10m;
client_body_buffer_size 128k;
client_body_temp_path /var/tmp/nginx/client_body 1 2;
}
Additional File and Request Handling Directives
Caching File Metadata:
The open_file_cache directives cache information about open files to reduce disk I/O.
open_file_cache max=5000 inactive=30s;
open_file_cache_valid 20s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
- Caches metadata for up to 5000 files.
- Removes entries not accessed within 30 seconds.
- Revalidates cache entries every 20 seconds.
- An entry must be accessed twice within the inactive period to be considered active.
- Caches file access errors.
Direct I/O:
directio size | off; enables direct I/O for file writes, bypassing the system cache for files larger than the specified size. Default is off.
Restricting HTTP Methods:
The limit_except block restricts HTTP methods within a location.
location /api {
limit_except GET POST {
allow 192.168.1.0/24;
deny all;
}
}
This configuration only allows the GET and POST methods for all clients, while other methods are restricted to the 192.168.1.0/24 subnet.