logo
🚀 DevOps

Nginx

Nginx Cheat Sheet - 快速参考指南,收录常用语法、命令与实践。

📂 分类 · DevOps🧭 Markdown 速查🏷️ 2 个标签
#nginx#server
向下滚动查看内容
返回全部 Cheat Sheets

Getting Started

Install & Service
  • Ubuntu/Debian
    SHELL
    滚动查看更多
    $ sudo apt update && sudo apt install -y nginx
    
  • RHEL/CentOS
    SHELL
    滚动查看更多
    $ sudo yum install -y epel-release nginx && sudo systemctl enable --now nginx
    
  • Service
    SHELL
    滚动查看更多
    $ sudo systemctl status nginx
    $ sudo systemctl reload nginx
    $ sudo systemctl restart nginx
    $ sudo nginx -t   # test config
    $ nginx -V        # built modules
    
Key Paths
  • /etc/nginx/nginx.conf (main config)
  • /etc/nginx/conf.d/*.conf (drop‑ins)
  • /etc/nginx/sites-available/ + sites-enabled/ (Debian style)
  • /var/www/html (default docroot)
  • logs: /var/log/nginx/access.log, /var/log/nginx/error.log
Minimal HTTP Server
NGINX
滚动查看更多
# /etc/nginx/conf.d/example.conf
server {
  listen 80;
  server_name example.com;
  root /var/www/example/public;

  location / {
    try_files $uri $uri/ =404;
  }
}

Config Structure

Core Blocks
  • main (global)
  • events (worker connections)
  • httpserverlocation
  • stream (TCP/UDP)
  • upstream (load balancers)
NGINX
滚动查看更多
user  www-data;
worker_processes auto;

events { worker_connections 1024; }

http {
  include       mime.types;
  default_type  application/octet-stream;
  sendfile      on;
  keepalive_timeout 65;

  # servers / includes go here...
}
Context & Order
  • location match order:
    1. Exact =
    2. ^~ (no regex if matched)
    3. Regex ~ / ~* (first match)
    4. Prefix (longest path)
  • try_files evaluates in order then falls back.
NGINX
滚动查看更多
location = /healthz { return 204; }
location ^~ /static/ { expires 7d; }
location ~* \.(png|jpg|css|js)$ { expires 7d; }
location / { try_files $uri $uri/ /index.html; }
Common Includes
NGINX
滚动查看更多
http {
  include /etc/nginx/conf.d/*.conf;
  include /etc/nginx/snippets/*.conf; # Ubuntu/Debian
}

Virtual Hosts & Redirects

Basic Server Block
NGINX
滚动查看更多
server {
  listen 80;
  server_name example.com www.example.com;
  root /var/www/example/public;
  index index.html index.htm;
}
Redirect HTTP→HTTPS
NGINX
滚动查看更多
server {
  listen 80;
  server_name example.com www.example.com;
  return 301 https://example.com$request_uri;
}
Canonical Host
NGINX
滚动查看更多
# Force non-www
server {
  listen 80;
  server_name www.example.com;
  return 301 $scheme://example.com$request_uri;
}

TLS/SSL

Basic TLS Server
NGINX
滚动查看更多
server {
  listen 443 ssl http2;
  server_name example.com;

  ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

  ssl_protocols TLSv1.2 TLSv1.3;
  ssl_prefer_server_ciphers off;

  root /var/www/example/public;
}
HSTS & Security Headers
NGINX
滚动查看更多
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
Let’s Encrypt (Certbot)
SHELL
滚动查看更多
$ sudo apt install -y certbot python3-certbot-nginx
$ sudo certbot --nginx -d example.com -d www.example.com
$ sudo systemctl list-timers | grep certbot   # auto-renew

Reverse Proxy

Basic Proxy
NGINX
滚动查看更多
upstream app {
  server 127.0.0.1:3000;
  # server unix:/run/app.sock; # alternative
}

server {
  listen 80;
  server_name api.example.com;

  location / {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_pass http://app;
  }
}
WebSockets / HTTP Upgrade
NGINX
滚动查看更多
location /socket.io/ {
  proxy_http_version 1.1;
  proxy_set_header Upgrade $http_upgrade;
  proxy_set_header Connection "upgrade";
  proxy_pass http://app;
}
Timeouts & Buffers
NGINX
滚动查看更多
proxy_connect_timeout 5s;
proxy_send_timeout    60s;
proxy_read_timeout    60s;
proxy_buffering       on;
proxy_buffers 16 16k;
proxy_busy_buffers_size 24k;

Static, Compression, Caching

Static Files
NGINX
滚动查看更多
location /assets/ {
  alias /var/www/example/assets/;
  access_log off;
  expires 7d;
  add_header Cache-Control "public, max-age=604800, immutable";
}
Gzip
NGINX
滚动查看更多
gzip on;
gzip_types text/plain text/css application/javascript application/json image/svg+xml;
gzip_min_length 1024;
gzip_comp_level 5;
(Optional) Brotli (if compiled)
NGINX
滚动查看更多
brotli on;
brotli_comp_level 5;
brotli_types text/plain text/css application/javascript application/json image/svg+xml;

Caching & Microcaching

Proxy Cache Zone
NGINX
滚动查看更多
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=micro:10m max_size=1g inactive=10m use_temp_path=off;
map $request_method $no_cache { default 0; POST 1; PUT 1; PATCH 1; DELETE 1; }
Use the Cache
NGINX
滚动查看更多
location /api/ {
  proxy_cache micro;
  proxy_cache_bypass $no_cache;
  proxy_no_cache $no_cache;
  proxy_cache_valid 200 301 302 10s;
  proxy_cache_valid any 1s;
  add_header X-Cache-Status $upstream_cache_status;
  proxy_pass http://app;
}
Conditional Bypass
NGINX
滚动查看更多
# Skip cache when logged in (example cookie)
map $http_cookie $logged_in {
  default 0;
  ~*"(session|auth|logged_in)" 1;
}
proxy_cache_bypass $logged_in;
proxy_no_cache $logged_in;

PHP‑FPM / FastCGI

Basic PHP Handler
NGINX
滚动查看更多
location ~ \.php$ {
  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
  fastcgi_param DOCUMENT_ROOT $realpath_root;
  fastcgi_pass unix:/run/php/php8.2-fpm.sock;
  fastcgi_buffers 16 16k;
  fastcgi_read_timeout 60s;
}
try_files Front Controller
NGINX
滚动查看更多
location / {
  try_files $uri $uri/ /index.php?$args;
}
Security Tips
NGINX
滚动查看更多
location ~* \.(?:ini|log|sh|sql|bak)$ { deny all; }
location ~ /\.(?!well-known) { deny all; }

Rewrites & Routing

try_files
NGINX
滚动查看更多
location / {
  try_files $uri $uri/ /index.html;
}
Regex Rewrites
NGINX
滚动查看更多
# Remove trailing slash (except root)
if ($request_uri ~* "^(.+)/+$") { return 301 $1; }

# Legacy path to new path
rewrite ^/old/(.*)$ /new/$1 permanent;
SPA / History API
NGINX
滚动查看更多
location / {
  try_files $uri /index.html;
}

Rate Limiting & DoS Mitigation

Request Rate
NGINX
滚动查看更多
# 10 req/s with burst 20 per IP
limit_req_zone $binary_remote_addr zone=reqs:10m rate=10r/s;

server {
  location /api/ {
    limit_req zone=reqs burst=20 nodelay;
  }
}
Concurrent Connections
NGINX
滚动查看更多
limit_conn_zone $binary_remote_addr zone=conns:10m;
server {
  location /download/ {
    limit_conn conns 10;
  }
}
Body Size & Timeouts
NGINX
滚动查看更多
client_max_body_size 25m;
client_body_timeout 30s;
keepalive_timeout 65s;

Security Headers & Access

Basic Hardening
NGINX
滚动查看更多
server_tokens off;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
Allow/Deny
NGINX
滚动查看更多
location /admin/ {
  allow 192.168.0.0/16;
  deny all;
}
CORS (Example)
NGINX
滚动查看更多
location /api/ {
  add_header Access-Control-Allow-Origin "https://app.example.com" always;
  add_header Access-Control-Allow-Credentials "true" always;
  if ($request_method = OPTIONS) {
    add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
    add_header Access-Control-Allow-Headers "Authorization, Content-Type";
    return 204;
  }
  proxy_pass http://app;
}

Logging & Debug

Formats
NGINX
滚动查看更多
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" "$http_x_forwarded_for" '
                '$request_time $upstream_response_time';

access_log /var/log/nginx/access.log main;
error_log  /var/log/nginx/error.log warn;
Per‑Location Logging
NGINX
滚动查看更多
location /healthz { access_log off; }
Debugging
SHELL
滚动查看更多
$ sudo nginx -t
$ sudo nginx -s reload
$ tail -f /var/log/nginx/error.log

Upstreams & LB

Strategies
DirectiveMeaning
(default)round‑robin
least_connleast connections
ip_hashsticky by client IP
hash keyhash by custom key

{.show-header}

Example Upstream
NGINX
滚动查看更多
upstream api_backends {
  least_conn;
  server 10.0.0.11:8080 max_fails=3 fail_timeout=30s;
  server 10.0.0.12:8080 max_fails=3 fail_timeout=30s;
  # server backup.example:8080 backup;
}
Health & Failover
NGINX
滚动查看更多
proxy_next_upstream error timeout http_502 http_503 http_504;
proxy_next_upstream_tries 3;

Useful Variables

Request & Client
VariableDescription
$hostHost header / server name
$server_nameChosen server_name
$remote_addrClient IP
$http_user_agentUser‑Agent
$request_methodGET/POST/...

{.show-header .bold-first}

Paths & Files
VariableDescription
$document_rootCurrent root
$realpath_rootSymlink‑resolved root
$request_uriPath + query
$uriNormalized URI
$argsRaw query string

{.show-header .bold-first}

Upstream
VariableDescription
$upstream_addrUpstream server(s)
$upstream_statusUpstream status
$upstream_response_timeTime from upstream

{.show-header .bold-first}

Stream (TCP/UDP)

TCP Proxy
NGINX
滚动查看更多
stream {
  upstream db {
    server 10.0.0.10:5432;
    server 10.0.0.11:5432;
  }
  server {
    listen 5432;
    proxy_pass db;
  }
}
UDP Proxy
NGINX
滚动查看更多
stream {
  server {
    listen 53 udp;
    proxy_responses 1;
    proxy_timeout 2s;
    proxy_pass 1.1.1.1:53;
  }
}
Access Control
NGINX
滚动查看更多
stream {
  server {
    listen 6379;
    allow 10.0.0.0/8;
    deny all;
    proxy_pass 127.0.0.1:6379;
  }
}

Snippets

Security Snippet
NGINX
滚动查看更多
# /etc/nginx/snippets/security.conf
server_tokens off;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
PHP Snippet
NGINX
滚动查看更多
# /etc/nginx/snippets/fastcgi-php.conf
location ~ \.php$ {
  include fastcgi_params;
  fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
  fastcgi_param DOCUMENT_ROOT $realpath_root;
  fastcgi_pass unix:/run/php/php8.2-fpm.sock;
}
Proxy Headers Snippet
NGINX
滚动查看更多
# /etc/nginx/snippets/proxy-headers.conf
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

相关 Cheat Sheets

1v1免费职业咨询
logo

Follow Us

linkedinfacebooktwitterinstagramweiboyoutubebilibilitiktokxigua

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-airwallex.png/image/layout/pay-alipay.png

地址

Level 10b, 144 Edward Street, Brisbane CBD(Headquarter)
Level 2, 171 La Trobe St, Melbourne VIC 3000
四川省成都市武侯区桂溪街道天府大道中段500号D5东方希望天祥广场B座45A13号
Business Hub, 155 Waymouth St, Adelaide SA 5000

Disclaimer

footer-disclaimerfooter-disclaimer

JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.

匠人学院网站上的所有内容,包括课程材料、徽标和匠人学院网站上提供的信息,均受澳大利亚政府知识产权法的保护。严禁未经授权使用、销售、分发、复制或修改。违规行为可能会导致法律诉讼。通过访问我们的网站,您同意尊重我们的知识产权。 JR Academy Pty Ltd 保留所有权利,包括专利、商标和版权。任何侵权行为都将受到法律追究。查看用户协议

© 2017-2025 JR Academy Pty Ltd. All rights reserved.

ABN 26621887572