Comprehensive Guide to Nginx Configuration, Optimization, and Deployment
This article provides a step‑by‑step tutorial on understanding, simplifying, annotating, and optimizing Nginx configuration files, covering global, events, and http blocks, practical deployment tips, reverse‑proxy setup, gzip compression, maintenance pages, multi‑site hosting, static‑dynamic separation, and essential command‑line operations for Linux servers.
Introduction
The author, a senior architect, explains that front‑end developers often need to understand Nginx, but many articles lack an overall view. This guide reorganizes the concepts and walks readers from the original configuration to a practical, simplified version.
Original nginx.conf and Explanation
The original configuration file contains many commented lines and spans over 118 lines, which can be overwhelming. The full content is shown below:
#user nobody;
worker_processes 1;
#error_log logs/error.log;
#error_log logs/error.log notice;
#error_log logs/error.log info;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
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 logs/access.log main;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
#gzip on;
server {
listen 80;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
# proxy_pass http://127.0.0.1;
#}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
#location ~ \.php$ {
# root html;
# fastcgi_pass 127.0.0.1:9000;
# fastcgi_index index.php;
# fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name;
# include fastcgi_params;
#}
# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
#location ~ /\.ht {
# deny all;
#}
}
# another virtual host using mix of IP-, name-, and port-based configuration
#
#server {
# listen 8000;
# listen somename:8080;
# server_name somename alias another.alias;
# location / {
# root html;
# index index.html index.htm;
# }
#}
# HTTPS server
#
#server {
# listen 443 ssl;
# server_name localhost;
# ssl_certificate cert.pem;
# ssl_certificate_key cert.key;
# ssl_session_cache shared:SSL:1m;
# ssl_session_timeout 5m;
# ssl_ciphers HIGH:!aNULL:!MD5;
# ssl_prefer_server_ciphers on;
# location / {
# root html;
# index index.html index.htm;
# }
#}
}After removing all comments, the configuration shrinks to only 22 lines, making it much easier to read.
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}Annotated Version
Comments are added to explain each directive:
# Number of Nginx worker processes, usually set to the number of CPU cores.
worker_processes 1;
# Events block start
events {
# Maximum connections per worker process (total connections = worker_processes * worker_connections)
worker_connections 1024;
}
# HTTP block – provides reverse‑proxy, load‑balancing, etc.
http {
# Include MIME types from external file
include mime.types;
# Default MIME type
default_type application/octet-stream;
# Enable efficient file transfer
sendfile on;
# Keep‑alive timeout in seconds
keepalive_timeout 65;
# Server block – a virtual host
server {
listen 80; # Listening port
server_name localhost; # Hostname
location / {
root html; # Document root
index index.html index.htm; # Default index files
}
# Error page routing
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html; # Directory for error page
}
}
}Overall Structure
The configuration can be divided into three logical parts:
Global block – settings that affect the whole Nginx server (user, worker_processes, PID file, logs, includes).
Events block – directives that influence network connections (worker_connections, event models).
HTTP block – the most frequently used part, containing server blocks, proxy settings, logging, timeouts, etc.
Global Block
Defines overall server behavior such as the number of worker processes, where the PID file is stored, and which external configuration files are included.
Events Block
Controls how Nginx handles connections, including the maximum number of simultaneous connections per worker.
HTTP Block
Contains the bulk of functional directives: MIME types, file serving, keep‑alive settings, and one or more server blocks that represent virtual hosts.
Simple Deployment
To get a website up quickly, modify only two places: set server_name to your domain or IP and change root to point to the directory containing your static files. Nginx will then serve index.html when users access the address.
Optimization Techniques
1. Front‑end History Mode 404 Fix
location / {
try_files $uri $uri/ /index.html;
}This ensures that when a user refreshes a SPA route, Nginx falls back to index.html instead of returning a 404.
2. Reverse Proxy
Typical cross‑origin solution for front‑ends:
# API endpoint
location /police/ {
proxy_pass http://192.168.1.182:8852/police/;
proxy_redirect default;
proxy_http_version 1.1;
proxy_connect_timeout 60;
proxy_send_timeout 60;
proxy_read_timeout 90;
}Requests starting with /police/ are forwarded to the backend service at the specified IP and port.
3. Enable Gzip Compression
gzip on; # default off
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
# Optional advanced settings
gzip_static on;
gzip_proxied any;
gzip_vary on;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;Compressing responses can roughly halve the size of static assets, improving load times.
4. Maintenance Page
# Uncomment the line below during maintenance and restart Nginx
# rewrite ^(.*)$ /maintainace.html break;This redirects all traffic to a static maintenance page while the site is being updated.
5. Multiple Sites on One IP
# First site (blog) on port 8080
server {
listen 8080;
root /data/www/hexo;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}
}
# Second site (live stream) on port 8081
server {
listen 8081;
root /data/www/geov;
index index.html;
location / {}
}Each server block represents a virtual host; ensure the corresponding ports are open in the firewall or cloud security group.
6. Static/Dynamic Separation
Static resources (HTML, JS, CSS, images) are served directly by Nginx, while dynamic API calls are proxied to backend services, reducing load on application servers.
location /image/ {
root /var/filecenter/;
}
location /static/ {
root /var/filecenter/;
}
location /car/ {
root /var/filecenter/;
}
location ~ .*(html|htm|gif|jpg|jpeg|bmp|png|ico|js|css)$ {
root /Users/dalaoyang/Downloads/static;
}Basic Nginx Commands
Install: yum install nginx
Check process: netstat -anput | grep nginx
Show listening ports: netstat -ntlp
Start: nginx
Reload configuration: nginx -s reload
Stop quickly: nginx -s stop
Graceful quit: nginx -s quit
Test configuration file: nginx -t
Note: Changes to nginx.conf require a reload/restart; updating only static files does not.
References
https://blog.csdn.net/qq_44691484/article/details/126354702
https://juejin.cn/post/6844904144235413512
https://github.com/rui-rui-an/nginxpages
The remainder of the original source contains promotional material for ChatGPT services, private consulting, and a community group, which is not part of the technical tutorial.
Top Architect
Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.
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.