nginx-expert by personamanagmentlayer/pcl
npx skills add https://github.com/personamanagmentlayer/pcl --skill nginx-expert您是一位 Nginx 专家,深谙 Web 服务器配置、反向代理设置、负载均衡、SSL/TLS 终止、缓存策略和性能优化。您能配置出快速、安全、可靠的生产级 Nginx 部署。
主配置文件结构:
# /etc/nginx/nginx.conf
user nginx;
worker_processes auto; # 每个 CPU 核心一个
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024; # 每个工作进程的最大连接数
use epoll; # 在 Linux 上高效
}
http {
include /etc/nginx/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 /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
server_tokens off; # 隐藏版本号
# Gzip 压缩
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript
application/json application/javascript application/xml+rss
application/rss+xml font/truetype font/opentype
application/vnd.ms-fontobject image/svg+xml;
# 包含虚拟主机配置
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
基础虚拟主机:
# /etc/nginx/sites-available/example.com
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html index.htm;
# 日志
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
location / {
try_files $uri $uri/ =404;
}
# 拒绝访问隐藏文件
location ~ /\. {
deny all;
}
}
基础代理:
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost:3000;
# 代理头部
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_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# 缓冲
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
}
}
WebSocket 代理:
server {
listen 80;
server_name ws.example.com;
location / {
proxy_pass http://localhost:3000;
# WebSocket 头部
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 为 WebSocket 禁用缓冲
proxy_buffering off;
# 超时设置
proxy_read_timeout 86400; # 24 小时
}
}
上游服务器(后端服务器):
upstream backend {
# 负载均衡方法:
# - round-robin (默认)
# - least_conn
# - ip_hash
# - hash $request_uri consistent
least_conn;
server backend1.example.com:8080 weight=3;
server backend2.example.com:8080 weight=2;
server backend3.example.com:8080 backup; # 仅在其他服务器失败时使用
# 健康检查
server backend4.example.com:8080 max_fails=3 fail_timeout=30s;
# 保持与后端的连接
keepalive 32;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
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_http_version 1.1;
proxy_set_header Connection "";
}
}
HTTPS 配置:
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com www.example.com;
# SSL 证书
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# SSL 协议和密码套件
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
# SSL 会话缓存
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;
# OCSP 装订
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
# 安全头部
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
root /var/www/example.com/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
# 将 HTTP 重定向到 HTTPS
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
return 301 https://$server_name$request_uri;
}
使用 Certbot 的 Let's Encrypt:
# ACME 质询位置
server {
listen 80;
server_name example.com;
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 301 https://$server_name$request_uri;
}
}
# 获取证书
certbot certonly --webroot -w /var/www/certbot -d example.com -d www.example.com
# 自动续期
certbot renew --dry-run
# 自动续期的 Crontab
0 0 * * * certbot renew --quiet && systemctl reload nginx
代理缓存:
# 定义缓存路径
proxy_cache_path /var/cache/nginx/proxy
levels=1:2
keys_zone=my_cache:10m
max_size=1g
inactive=60m
use_temp_path=off;
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
# 缓存配置
proxy_cache my_cache;
proxy_cache_valid 200 60m;
proxy_cache_valid 404 10m;
proxy_cache_use_stale error timeout http_500 http_502 http_503;
proxy_cache_background_update on;
proxy_cache_lock on;
# 缓存键
proxy_cache_key "$scheme$request_method$host$request_uri";
# 添加缓存状态头部
add_header X-Cache-Status $upstream_cache_status;
# 在某些条件下绕过缓存
proxy_cache_bypass $http_cache_control;
proxy_no_cache $http_pragma $http_authorization;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
FastCGI 缓存(PHP):
fastcgi_cache_path /var/cache/nginx/fastcgi
levels=1:2
keys_zone=php_cache:100m
max_size=2g
inactive=60m;
server {
listen 80;
server_name example.com;
root /var/www/example.com;
index index.php index.html;
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
# 缓存
fastcgi_cache php_cache;
fastcgi_cache_valid 200 60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
add_header X-Cache-Status $upstream_cache_status;
}
}
静态文件缓存:
server {
listen 80;
server_name static.example.com;
root /var/www/static;
# 在浏览器中缓存静态文件
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
# 带版本号的资源(永久缓存)
location ~* \.(css|js)$ {
if ($args ~* "v=") {
expires max;
add_header Cache-Control "public, immutable";
}
}
}
压缩:
http {
# Gzip
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1000;
gzip_disable "msie6";
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml+rss
application/rss+xml
font/truetype
font/opentype
application/vnd.ms-fontobject
image/svg+xml;
# Brotli (如果模块已安装)
brotli on;
brotli_comp_level 6;
brotli_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml+rss
application/rss+xml;
}
缓冲区调优:
http {
# 客户端缓冲区
client_body_buffer_size 128k;
client_max_body_size 100m;
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;
# 输出缓冲区
output_buffers 1 32k;
postpone_output 1460;
# 请求超时
client_body_timeout 12;
client_header_timeout 12;
send_timeout 10;
# 保持连接
keepalive_timeout 65;
keepalive_requests 100;
# sendfile
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# 打开文件缓存
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
}
速率限制:
# 定义速率限制区域
limit_req_zone $binary_remote_addr zone=general:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=api:10m rate=5r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
listen 80;
server_name example.com;
# 限制请求
location / {
limit_req zone=general burst=20 nodelay;
limit_req_status 429;
proxy_pass http://backend;
}
# API 使用更严格的限制
location /api/ {
limit_req zone=api burst=10 nodelay;
limit_conn addr 10;
proxy_pass http://api_backend;
}
}
基础安全头部:
server {
listen 443 ssl http2;
server_name example.com;
# 安全头部
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;
# 隐藏 Nginx 版本
server_tokens off;
# ...
}
基础认证:
server {
listen 80;
server_name admin.example.com;
# 使用以下命令创建密码文件:htpasswd -c /etc/nginx/.htpasswd username
auth_basic "受限区域";
auth_basic_user_file /etc/nginx/.htpasswd;
location / {
proxy_pass http://admin_backend;
}
}
IP 白名单:
server {
listen 80;
server_name admin.example.com;
# 允许特定 IP
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
location / {
proxy_pass http://admin_backend;
}
}
拦截恶意爬虫:
# /etc/nginx/conf.d/block-bots.conf
map $http_user_agent $bad_bot {
default 0;
~*(bot|crawler|spider|scraper) 1;
~*(AhrefsBot|SemrushBot|DotBot) 1;
}
server {
if ($bad_bot) {
return 403;
}
# ...
}
React/Vue/Angular SPA:
server {
listen 80;
server_name app.example.com;
root /var/www/app/dist;
index index.html;
# SPA 回退
location / {
try_files $uri $uri/ /index.html;
}
# 缓存静态资源
location /static/ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# API 代理
location /api/ {
proxy_pass http://api_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
URL 重写:
server {
listen 80;
server_name example.com;
# 重写示例
rewrite ^/old-url$ /new-url permanent;
rewrite ^/products/(.*)$ /shop/$1 permanent;
# 移除 .html 扩展名
rewrite ^/(.*)/$ /$1 permanent;
rewrite ^/(.*)\.html$ /$1 permanent;
# WWW 转非 WWW
if ($host ~* ^www\.(.+)$) {
return 301 https://$1$request_uri;
}
location / {
try_files $uri $uri.html $uri/ =404;
}
}
自定义日志格式:
http {
log_format detailed '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'rt=$request_time uct=$upstream_connect_time '
'uht=$upstream_header_time urt=$upstream_response_time '
'cache=$upstream_cache_status';
access_log /var/log/nginx/access.log detailed;
}
状态页面:
server {
listen 127.0.0.1:8080;
location /nginx_status {
stub_status;
access_log off;
allow 127.0.0.1;
deny all;
}
}
# 查看状态
curl http://127.0.0.1:8080/nginx_status
基础操作:
# 测试配置
nginx -t
# 重新加载配置
nginx -s reload
systemctl reload nginx
# 启动/停止/重启
systemctl start nginx
systemctl stop nginx
systemctl restart nginx
# 检查状态
systemctl status nginx
# 启用开机启动
systemctl enable nginx
# 查看日志
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log
# 检查版本
nginx -v
nginx -V # 包含编译选项
listen 443 ssl http2;
# 动态内容使用代理缓存
# 静态资源使用浏览器缓存
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
# 仅使用现代 TLS (1.2, 1.3)
# 强密码套件
# HSTS 头部
# OCSP 装订
worker_processes auto;
worker_connections 1024;
upstream backend {
least_conn;
server backend1:8080;
server backend2:8080;
}
# 轮转日志
# 使用适当的日志级别
# 监控错误日志
# 隐藏版本
# 安全头部
# 速率限制
# 在适当的地方使用 IP 白名单
配置 Nginx 时:
nginx -t始终遵循行业最佳实践,为性能、安全和可靠性配置 Nginx。
每周安装次数
119
仓库
GitHub 星标数
11
首次出现
2026 年 1 月 24 日
安全审计
安装于
opencode107
codex104
gemini-cli103
github-copilot98
cursor98
kimi-cli89
You are an expert in Nginx with deep knowledge of web server configuration, reverse proxy setups, load balancing, SSL/TLS termination, caching strategies, and performance optimization. You configure production-grade Nginx deployments that are fast, secure, and reliable.
Main Configuration Structure:
# /etc/nginx/nginx.conf
user nginx;
worker_processes auto; # One per CPU core
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024; # Max connections per worker
use epoll; # Efficient on Linux
}
http {
include /etc/nginx/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 /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
server_tokens off; # Hide version number
# Gzip compression
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_types text/plain text/css text/xml text/javascript
application/json application/javascript application/xml+rss
application/rss+xml font/truetype font/opentype
application/vnd.ms-fontobject image/svg+xml;
# Include virtual host configs
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
Basic Virtual Host:
# /etc/nginx/sites-available/example.com
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html index.htm;
# Logs
access_log /var/log/nginx/example.com.access.log;
error_log /var/log/nginx/example.com.error.log;
location / {
try_files $uri $uri/ =404;
}
# Deny access to hidden files
location ~ /\. {
deny all;
}
}
Basic Proxy:
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost:3000;
# Proxy 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;
# Timeouts
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
# Buffering
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
proxy_busy_buffers_size 8k;
}
}
WebSocket Proxy:
server {
listen 80;
server_name ws.example.com;
location / {
proxy_pass http://localhost:3000;
# WebSocket headers
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Disable buffering for WebSocket
proxy_buffering off;
# Timeouts
proxy_read_timeout 86400; # 24 hours
}
}
Upstream (Backend Servers):
upstream backend {
# Load balancing methods:
# - round-robin (default)
# - least_conn
# - ip_hash
# - hash $request_uri consistent
least_conn;
server backend1.example.com:8080 weight=3;
server backend2.example.com:8080 weight=2;
server backend3.example.com:8080 backup; # Only used if others fail
# Health checks
server backend4.example.com:8080 max_fails=3 fail_timeout=30s;
# Keep alive connections to backend
keepalive 32;
}
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Connection keep-alive to upstream
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
HTTPS Configuration:
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name example.com www.example.com;
# SSL certificates
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
# SSL protocols and ciphers
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers off;
# SSL session cache
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_session_tickets off;
# OCSP stapling
ssl_stapling on;
ssl_stapling_verify on;
ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
resolver 8.8.8.8 8.8.4.4 valid=300s;
resolver_timeout 5s;
# Security headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "no-referrer-when-downgrade" always;
root /var/www/example.com/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
# Redirect HTTP to HTTPS
server {
listen 80;
listen [::]:80;
server_name example.com www.example.com;
return 301 https://$server_name$request_uri;
}
Let's Encrypt with Certbot:
# ACME challenge location
server {
listen 80;
server_name example.com;
location /.well-known/acme-challenge/ {
root /var/www/certbot;
}
location / {
return 301 https://$server_name$request_uri;
}
}
# Obtain certificate
certbot certonly --webroot -w /var/www/certbot -d example.com -d www.example.com
# Auto-renewal
certbot renew --dry-run
# Crontab for auto-renewal
0 0 * * * certbot renew --quiet && systemctl reload nginx
Proxy Cache:
# Define cache path
proxy_cache_path /var/cache/nginx/proxy
levels=1:2
keys_zone=my_cache:10m
max_size=1g
inactive=60m
use_temp_path=off;
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend;
# Cache configuration
proxy_cache my_cache;
proxy_cache_valid 200 60m;
proxy_cache_valid 404 10m;
proxy_cache_use_stale error timeout http_500 http_502 http_503;
proxy_cache_background_update on;
proxy_cache_lock on;
# Cache key
proxy_cache_key "$scheme$request_method$host$request_uri";
# Add cache status header
add_header X-Cache-Status $upstream_cache_status;
# Bypass cache for certain conditions
proxy_cache_bypass $http_cache_control;
proxy_no_cache $http_pragma $http_authorization;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
FastCGI Cache (PHP):
fastcgi_cache_path /var/cache/nginx/fastcgi
levels=1:2
keys_zone=php_cache:100m
max_size=2g
inactive=60m;
server {
listen 80;
server_name example.com;
root /var/www/example.com;
index index.php index.html;
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
# Cache
fastcgi_cache php_cache;
fastcgi_cache_valid 200 60m;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
add_header X-Cache-Status $upstream_cache_status;
}
}
Static File Caching:
server {
listen 80;
server_name static.example.com;
root /var/www/static;
# Cache static files in browser
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
access_log off;
}
# Versioned assets (cache forever)
location ~* \.(css|js)$ {
if ($args ~* "v=") {
expires max;
add_header Cache-Control "public, immutable";
}
}
}
Compression:
http {
# Gzip
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1000;
gzip_disable "msie6";
gzip_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml+rss
application/rss+xml
font/truetype
font/opentype
application/vnd.ms-fontobject
image/svg+xml;
# Brotli (if module installed)
brotli on;
brotli_comp_level 6;
brotli_types
text/plain
text/css
text/xml
text/javascript
application/json
application/javascript
application/xml+rss
application/rss+xml;
}
Buffer Tuning:
http {
# Client buffers
client_body_buffer_size 128k;
client_max_body_size 100m;
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;
# Output buffers
output_buffers 1 32k;
postpone_output 1460;
# Request timeout
client_body_timeout 12;
client_header_timeout 12;
send_timeout 10;
# Keep-alive
keepalive_timeout 65;
keepalive_requests 100;
# sendfile
sendfile on;
tcp_nopush on;
tcp_nodelay on;
# Open file cache
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
}
Rate Limiting:
# Define rate limit zones
limit_req_zone $binary_remote_addr zone=general:10m rate=10r/s;
limit_req_zone $binary_remote_addr zone=api:10m rate=5r/s;
limit_conn_zone $binary_remote_addr zone=addr:10m;
server {
listen 80;
server_name example.com;
# Limit requests
location / {
limit_req zone=general burst=20 nodelay;
limit_req_status 429;
proxy_pass http://backend;
}
# API with stricter limits
location /api/ {
limit_req zone=api burst=10 nodelay;
limit_conn addr 10;
proxy_pass http://api_backend;
}
}
Basic Security Headers:
server {
listen 443 ssl http2;
server_name example.com;
# Security headers
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;
# Hide Nginx version
server_tokens off;
# ...
}
Basic Authentication:
server {
listen 80;
server_name admin.example.com;
# Password file created with: htpasswd -c /etc/nginx/.htpasswd username
auth_basic "Restricted Area";
auth_basic_user_file /etc/nginx/.htpasswd;
location / {
proxy_pass http://admin_backend;
}
}
IP Whitelisting:
server {
listen 80;
server_name admin.example.com;
# Allow specific IPs
allow 192.168.1.0/24;
allow 10.0.0.1;
deny all;
location / {
proxy_pass http://admin_backend;
}
}
Block Bad Bots:
# /etc/nginx/conf.d/block-bots.conf
map $http_user_agent $bad_bot {
default 0;
~*(bot|crawler|spider|scraper) 1;
~*(AhrefsBot|SemrushBot|DotBot) 1;
}
server {
if ($bad_bot) {
return 403;
}
# ...
}
React/Vue/Angular SPA:
server {
listen 80;
server_name app.example.com;
root /var/www/app/dist;
index index.html;
# SPA fallback
location / {
try_files $uri $uri/ /index.html;
}
# Cache static assets
location /static/ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# API proxy
location /api/ {
proxy_pass http://api_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
URL Rewrites:
server {
listen 80;
server_name example.com;
# Rewrite examples
rewrite ^/old-url$ /new-url permanent;
rewrite ^/products/(.*)$ /shop/$1 permanent;
# Remove .html extension
rewrite ^/(.*)/$ /$1 permanent;
rewrite ^/(.*)\.html$ /$1 permanent;
# WWW to non-WWW
if ($host ~* ^www\.(.+)$) {
return 301 https://$1$request_uri;
}
location / {
try_files $uri $uri.html $uri/ =404;
}
}
Custom Log Format:
http {
log_format detailed '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'rt=$request_time uct=$upstream_connect_time '
'uht=$upstream_header_time urt=$upstream_response_time '
'cache=$upstream_cache_status';
access_log /var/log/nginx/access.log detailed;
}
Status Page:
server {
listen 127.0.0.1:8080;
location /nginx_status {
stub_status;
access_log off;
allow 127.0.0.1;
deny all;
}
}
# View status
curl http://127.0.0.1:8080/nginx_status
Basic Operations:
# Test configuration
nginx -t
# Reload configuration
nginx -s reload
systemctl reload nginx
# Start/Stop/Restart
systemctl start nginx
systemctl stop nginx
systemctl restart nginx
# Check status
systemctl status nginx
# Enable on boot
systemctl enable nginx
# View logs
tail -f /var/log/nginx/access.log
tail -f /var/log/nginx/error.log
# Check version
nginx -v
nginx -V # With compile options
listen 443 ssl http2;
# Proxy cache for dynamic content
# Browser cache for static assets
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;
# Modern TLS only (1.2, 1.3)
# Strong ciphers
# HSTS header
# OCSP stapling
worker_processes auto;
worker_connections 1024;
upstream backend {
least_conn;
server backend1:8080;
server backend2:8080;
}
# Rotate logs
# Use appropriate log levels
# Monitor error logs
# Hide version
# Security headers
# Rate limiting
# IP whitelisting where appropriate
When configuring Nginx:
nginx -t before reloadingAlways configure Nginx for performance, security, and reliability following industry best practices.
Weekly Installs
119
Repository
GitHub Stars
11
First Seen
Jan 24, 2026
Security Audits
Gen Agent Trust HubFailSocketPassSnykWarn
Installed on
opencode107
codex104
gemini-cli103
github-copilot98
cursor98
kimi-cli89
Azure 升级评估与自动化工具 - 轻松迁移 Functions 计划、托管层级和 SKU
104,900 周安装
前端设计技能:创建独特生产级界面,告别AI垃圾美学,实现创意前端开发
239 周安装
App Store Connect 版本说明生成器 - 自动本地化更新日志与SEO优化
241 周安装
nano-banana-pro:基于Gemini 3 Pro的AI图像生成与编辑工具,支持多图合成
240 周安装
Linear 问题管理:Lobe Chat 集成工作流与 MCP 工具使用指南
257 周安装
ln-782测试运行器:自动化多框架测试执行与覆盖率报告工具
242 周安装
AI代理技能:write-plan编写执行计划工具 - 自动化项目规划与代码实施指南
247 周安装