Comprehensive Guide to Nginx: HTTP Server, Static Serving, Reverse Proxy, Load Balancing, and Advanced Directives
This article provides a detailed tutorial on configuring Nginx as an HTTP server, setting up static file serving, implementing reverse proxy, configuring various load‑balancing strategies, and using advanced directives such as location matching, return, rewrite, error_page, and logging.
1. HTTP Server
Nginx can serve static resources directly; for a website consisting only of static pages, placing an html directory under the document root (e.g., /usr/local/var/www ) and adding a test.html file is sufficient.
Configure the server block in nginx.conf as follows:
user mengday staff;
http {
server {
listen 80;
server_name localhost;
client_max_body_size 1024M;
# default location
location / {
root /usr/local/var/www/html;
index index.html index.htm;
}
}
}Test the configuration by accessing http://localhost/ (maps to /usr/local/var/www/index.html ) and http://localhost/test.html (maps to /usr/local/var/www/html/test.html ).
Note: If you encounter a 403 Forbidden error when accessing images, adjust the user directive in nginx.conf (e.g., user root; on Linux or user username ; on macOS) and reload Nginx.
Key directives explained:
server : defines a virtual server; multiple server blocks can exist within http .
listen : specifies IP address and port to listen on.
server_name : sets the domain name.
location : maps URI patterns to configuration blocks; can use exact strings, prefixes, or regular expressions.
root : defines the filesystem path for static files.
index : specifies default index files.
2. Static Server
In corporate environments, a static server often provides an upload function for shared assets. Create images and img directories under /usr/local/var/www and place a test.jpg in each.
http {
server {
listen 80;
server_name localhost;
set $doc_root /usr/local/var/www;
# default location
location / {
root /usr/local/var/www/html;
index index.html index.htm;
}
location ^~ /images/ {
root $doc_root;
}
location ~* \.(gif|jpg|jpeg|png|bmp|ico|swf|css|js)$ {
root $doc_root/img;
}
}
}Two common mapping methods for static resources:
Path‑based mapping (e.g., /images/ ).
Extension‑based mapping (e.g., .jpg , .png ).
Requests to http://localhost/test.jpg resolve to $doc_root/img , while http://localhost/images/test.jpg matches the higher‑priority ^~ location.
Location Priority
When multiple location blocks match a request, Nginx selects the one with the highest priority, which depends on the expression type rather than the order in the file. The priority order is:
location = / (exact match) – highest.
location ^~ /path/ (prefix, stop search).
location ~ / ~* (regular expressions – longest match wins).
Standard prefix matches (e.g., location /documents/ ).
location / (catch‑all).
location = / {
# exact match
[ configuration A ]
}
location / {
# matches any URI starting with /
[ configuration B ]
}
location /documents/ {
# matches URIs starting with /documents/
[ configuration C ]
}
location ^~ /images/ {
# high‑priority prefix match
[ configuration D ]
}
location ~* \.(gif|jpg|jpeg)$ {
# case‑insensitive regex match
[ configuration E ]
}
location = /test.htm {
root /usr/local/var/www/htm;
index index.htm;
}3. Reverse Proxy
The reverse proxy feature forwards client requests to internal services. It is implemented with the proxy_pass directive.
Example: forwarding all traffic on port 80 to a Java web application listening on port 8081.
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://localhost:8081;
proxy_set_header Host $host:$server_port;
# forward client IP
proxy_set_header X-Forwarded-For $remote_addr;
# fallback to other upstreams on error
proxy_next_upstream error timeout invalid_header http_500 http_502 http_503;
}
}Visiting http://localhost now serves the application at localhost:8081 .
4. Load Balancing
Nginx can distribute requests across multiple backend servers using the upstream block. Five common strategies are covered:
1) Round Robin (default)
Requests are sent to backends in a cyclic order.
upstream web_servers {
server localhost:8081;
server localhost:8082;
}
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://web_servers;
proxy_set_header Host $host:$server_port;
}
}2) Weighted Round Robin
Assigns a weight to each server; traffic proportionally follows the weight.
upstream test {
server localhost:8081 weight=1;
server localhost:8082 weight=3;
server localhost:8083 weight=4 backup;
}The backup server is used only when all primary servers fail.
3) IP Hash
Ensures a client IP always maps to the same backend, useful for session‑affinity.
upstream test {
ip_hash;
server localhost:8080;
server localhost:8081;
}4) Fair (third‑party)
Distributes requests based on backend response time, favoring faster servers.
upstream backend {
fair;
server localhost:8080;
server localhost:8081;
}5) URL Hash (third‑party)
Hashes the request URI so that the same URL consistently reaches the same backend, useful for caching.
upstream backend {
hash $request_uri;
hash_method crc32;
server localhost:8080;
server localhost:8081;
}5. Static‑Dynamic Separation
Separating static assets from dynamic requests enables caching of immutable resources.
upstream web_servers {
server localhost:8081;
server localhost:8082;
}
server {
listen 80;
server_name localhost;
set $doc_root /usr/local/var/www;
location ~* \.(gif|jpg|jpeg|png|bmp|ico|swf|css|js)$ {
root $doc_root/img;
}
location / {
proxy_pass http://web_servers;
proxy_set_header Host $host:$server_port;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root $doc_root;
}
}6. Other Useful Directives
6.1 return
Returns a status code and optional redirect URL.
location /permanently/moved/url {
return 301 http://www.example.com/moved/here;
}6.2 rewrite
Modifies the request URI using a regular expression.
location /users/ {
rewrite ^/users/(.*)$ /show?user=$1 break;
}6.3 error_page
Defines custom error pages.
error_page 404 /404.html;6.4 Logging
Enable gzip compression and configure log format.
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 /usr/local/etc/nginx/logs/host.access.log main;
gzip on;6.5 deny
Block access to specific file types.
# deny access to certain directories
location ~* \.(txt|doc)$ {
root $doc_root;
deny all;
}6.6 Built‑in Variables
Nginx provides many built‑in variables (e.g., $args , $content_length , $host , $remote_addr , $request_uri , etc.) that can be used in configuration for dynamic behavior.
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.