Changelog

Nginx configuration quick reference

Nginx Common Configuration Snippets Quick Reference, Quickly Find and Copy Configuration Code

Basic Configuration
7

Automatically Set Number of Worker Processes (Usually Equal to CPU Core Count)

worker_processes auto;

Set Maximum Number of Connections per Worker Process

events {
    worker_connections 1024;
}

Include MIME Type Configuration

include /etc/nginx/mime.types;
default_type application/octet-stream;

Enable Efficient File Transfer

sendfile on;
tcp_nopush on;
tcp_nodelay on;

Set Keepalive Timeout

keepalive_timeout 65;

Set Maximum Size of Client Request Body

client_max_body_size 100M;

Hide Nginx Version Number

server_tokens off;
Server Block
6

Basic Server Block Configuration

server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    index index.html;
}

Configure Multiple Domains

server_name example.com www.example.com;

Configure Wildcard Domain

server_name *.example.com;

Set Default Server

listen 80 default_server;

Listen on IPv6 Address

listen [::]:80;

Set Root Directory or Alias

root /var/www/html;
# Or use alias
alias /var/www/files/;
Location Matching
7

Exact Path Match

location = /path {
    # Exact Match
}

Prefix Path Match

location /api/ {
    # Prefix Match
}

Regular Expression Match

location ~ \.php$ {
    # Regular Expression Match (Case Sensitive)
}

Case-Insensitive Regular Expression Match

location ~* \.\(jpg|jpeg|png|gif\)$ {
    # Regular Expression Match (Case Insensitive)
}

Priority prefix matching (higher priority than regex)

location ^~ /images/ { #δΌ˜ε…ˆε‰ηΌ€εŒΉι… }

Try files in order (commonly used for SPA applications)

location / { try_files $uri $uri/ /index.html; }

Only allow internal requests to access

location /internal/ { internal; }
Reverse Proxy
7

Basic reverse proxy configuration

location /api/ { proxy_pass http://backend:3000/; }

Set proxy request headers

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;

WebSocket proxy configuration

location /ws/ { proxy_pass http://backend:3000/; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }

Define upstream server group

upstream backend { server 127.0.0.1:3000; server 127.0.0.1:3001; keepalive 32; }

Load balancing configuration

upstream backend { least_conn; # or ip_hash; server 127.0.0.1:3000; server 127.0.0.1:3001; }

Proxy timeout settings

proxy_connect_timeout 60s; proxy_send_timeout 60s; proxy_read_timeout 60s;

Proxy buffer configuration

proxy_buffering on; proxy_buffer_size 4k; proxy_buffers 8 4k;
SSL/HTTPS
7

Basic SSL configuration

server { listen 443 ssl http2; ssl_certificate /path/to/cert.pem; ssl_certificate_key /path/to/key.pem; }

Set SSL protocol version

ssl_protocols TLSv1.2 TLSv1.3;

Set cipher suites

ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256; ssl_prefer_server_ciphers on;

SSL session cache

ssl_session_cache shared:SSL:10m; ssl_session_timeout 1d;

HTTP redirect to HTTPS

server { listen 80; server_name example.com; return 301 https://$server_name$request_uri; }

Enable HSTS

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

Enable OCSP Stapling

ssl_stapling on; ssl_stapling_verify on; resolver 8.8.8.8 8.8.4.4 valid=300s;
Cache Configuration
5

Static resource caching

location ~* \.\(css|js|jpg|jpeg|png|gif|ico|svg|woff|woff2\)$ { expires 30d; add_header Cache-Control "public, immutable"; }

Disable caching

location /api/ { add_header Cache-Control "no-store, no-cache, must-revalidate"; }

Proxy cache configuration

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g; location / { proxy_cache my_cache; proxy_cache_valid 200 1d; }

Enable ETag

etag on;

Enable conditional requests

if_modified_since before;
Gzip Compression
4

Basic Gzip compression configuration

gzip on; gzip_vary on; gzip_min_length 1024; gzip_comp_level 6;

Set MIME types to compress

gzip_types text/plain text/css text/xml text/javascript application/javascript application/json application/xml;

Enable compression for proxy requests

gzip_proxied any;

Enable pre-compressed files

gzip_static on;
Security Configuration
6

CORS Cross-origin Configuration

add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,Content-Type";

XSS and Clickjacking Protection

add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options SAMEORIGIN;

Content Security Policy

add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'";

Request Rate Limiting

limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;

location /api/ {
    limit_req zone=one burst=20 nodelay;
}

Block Access to Hidden Files

location ~ /\. {
    deny all;
}

IP Whitelist

location /admin/ {
    allow 192.168.1.0/24;
    deny all;
}
Log Configuration
6

Access Log Configuration

access_log /var/log/nginx/access.log;

Error Log Configuration

error_log /var/log/nginx/error.log warn;

Custom 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"';

JSON Format Log

log_format json escape=json '{"time":"$time_iso8601","ip":"$remote_addr","method":"$request_method","uri":"$uri","status":$status}';

Disable Access Log

access_log off;

Conditional Logging (Log only errors)

map $status $loggable {
    ~^[23] 0;
    default 1;
}
access_log /var/log/nginx/access.log combined if=$loggable;
Performance Optimization
5

File Descriptor Cache

open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;

Enable Multi-Connection Accept and epoll

events {
    multi_accept on;
    use epoll;
}

FastCGI Cache

fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=fastcgi:10m;

location ~ \.php$ {
    fastcgi_cache fastcgi;
    fastcgi_cache_valid 200 1h;
}

Connection Limiting

limit_conn_zone $binary_remote_addr zone=addr:10m;
limit_conn addr 100;

Timeout Optimization

client_body_timeout 12;
client_header_timeout 12;
send_timeout 10;

πŸ“–Tool Introduction

Nginx Configuration Quick Reference is a fast-reference tool designed for web developers and operations personnel. It covers all commonly used configuration snippets from basic to advanced, organized by functionality, supporting quick search and one-click copy. Whether you are a beginner in Nginx or an experienced operations engineer, you can quickly find the required configuration code here.

Key Features

1
10 major categories covering all common Nginx configuration scenarios
2
Over 60 commonly used configuration snippets, comprehensively covering from basic to advanced
3
Supports keyword search, quickly locating required configurations
4
One-click copy of configuration code, improving work efficiency
5
Clear Chinese explanations, easy to understand and learn
6
Categorized browsing and filtering, quickly finding relevant configurations
7
Responsive design, supports mobile viewing
8
Local execution, usable without internet

❓Frequently Asked Questions

πŸ”—Related Tools

Cron Expression Parser

Validate cron syntax and preview upcoming schedules.

Developer Tools
Try Now

JSON to CSV

Convert JSON data to CSV format

Converters
Try Now

JSON to YAML

Convert JSON data to YAML format

Converters
Try Now

JSON to XML

Convert JSON data to XML format

Converters
Try Now

YAML to JSON

Convert YAML configuration to JSON data

Converters
Try Now

JSON Formatter

Format, validate and minify JSON data

JSON Utilities
Try Now

JSON Visualizer

Display JSON data in tree structure

JSON Utilities
Try Now

JSON Data Generator

Generate mock JSON data for testing

JSON Utilities
Try Now

i18n JSON Translator

Translate entire JSON locale files in one go. Paste your base content, choose target languages, and the tool will call your OpenRouter-powered API with flattened keys.

JSON Utilities
Try Now

JSON Diff Comparison

Compare differences between two JSON data

JSON Utilities
Try Now

QR Code Generator

Generate custom QR code images

Image Tools
Try Now

SVG Placeholder Generator

Generate custom SVG placeholder images

Image Tools
Try Now

Base64 Image Converter

Convert images to Base64 encoding and vice versa

Image Tools
Try Now

UUID Generator

Generate UUID unique identifiers in batch

Generator Tools
Try Now

Password Generator

Generate secure and reliable random passwords

Generator Tools
Try Now

Base64 Encoder/Decoder

Base64 string encoding and decoding tool

Text Tools
Try Now

URL Encoder/Decoder

URL string encoding and decoding tool

Text Tools
Try Now

MD5 Hash Generator

Generate MD5 hash values from text

Crypto Tools
Try Now

SHA256 Hash Generator

Generate SHA256 hash values from text

Crypto Tools
Try Now

SHA1 Hash Generator

Generate SHA1 hash values from text

Crypto Tools
Try Now

Hex Encoder/Decoder

Hexadecimal string encoding and decoding tool

Crypto Tools
Try Now

Binary Encoder/Decoder

Binary string encoding and decoding tool

Crypto Tools
Try Now

AES Encrypt/Decrypt

AES symmetric encryption algorithm tool

Crypto Tools
Try Now

RSA Encrypt/Decrypt

RSA asymmetric encryption algorithm tool

Crypto Tools
Try Now

HMAC Generator

HMAC message authentication code generation tool

Crypto Tools
Try Now

IP Address Lookup

Query geographical location and network information of IP addresses

Network Tools
Try Now

Milliseconds Time Converter

Convert between millisecond timestamps and formatted date strings.

Time Tools
Try Now
Showing 27 of 28 tools
    Nginx Configuration Cheat Sheet - Quick Reference for Common Configurations - IT Tools Collection