Nginx 是一个高性能的 HTTP 和反向代理服务器,也是一个 IMAP/POP3 代理服务器,本文介绍Nginx 配置速查手册:核心语法与实战案例,感兴趣的朋友一起看看吧
当你需要在几分钟内快速配置 Nginx 时,本文就是你的速查手册。每个知识点控制在 3 行以内,核心语法与常用示例一目了然。
核心语法速查
基础配置
| 语法 | 说明 | 示例 |
|---|
user | 设置运行 Nginx 的用户和组 | user nobody; |
worker_processes | 设置工作进程数 | worker_processes 4; |
error_log | 指定错误日志文件位置 | error_log /var/log/nginx/error.log warn; |
pid | 指定 Nginx 进程 ID 文件位置 | pid /var/run/nginx.pid; |
事件模块
| 语法 | 说明 | 示例 |
|---|
events | 事件处理块 | events {
worker_connections 1024;
} |
worker_connections | 每个工作进程的最大连接数 | worker_connections 1024; |
HTTP 核心模块
| 语法 | 说明 | 示例 |
|---|
http | HTTP 块,包含多个上下文 | http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
gzip on;
} |
include | 包含其他配置文件 | include /etc/nginx/mime.types; |
default_type | 设置默认的 MIME 类型 | default_type application/octet-stream; |
sendfile | 使用 sendfile 优化文件传输 | sendfile on; |
keepalive_timeout | 设置长连接的超时时间 | keepalive_timeout 65; |
gzip | 开启或关闭 Gzip 压缩 | gzip on; |
服务器块
| 语法 | 说明 | 示例 |
|---|
server | 定义一个虚拟主机 | server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html index.htm;
} |
listen | 监听的端口或 IP | listen 80; |
server_name | 虚拟主机的域名 | server_name example.com; |
root | 站点根目录 | root /var/www/html; |
index | 默认索引文件 | index index.html index.htm; |
位置块
| 语法 | 说明 | 示例 |
|---|
location | 匹配 URL 并定义处理方式 | location / {
try_files $uri $uri/ =404;
} |
try_files | 尝试按顺序查找文件,如果都未找到则返回最后一个参数指定的状态码或 URL | try_files $uri $uri/ =404; |
反向代理
| 语法 | 说明 | 示例 |
|---|
proxy_pass | 将请求转发到后端服务器 | location /api {
proxy_pass http://backend_server;
} |
proxy_set_header | 设置转发请求头 | proxy_set_header Host $host; |
重定向
| 语法 | 说明 | 示例 |
|---|
return | 直接返回一个状态码或 URL | location /old {
return 301 http://example.com/new;
} |
rewrite | URL 重写 | rewrite ^/old/([a-z]+)$ /new/$1 permanent; |
负载均衡
| 语法 | 说明 | 示例 |
|---|
upstream | 定义后端服务器池 | upstream backend {
server backend1.example.com;
server backend2.example.com;
} |
least_conn | 最少连接数调度 | upstream backend {
least_conn;
server backend1.example.com;
server backend2.example.com;
} |
ip_hash | 基于客户端 IP 调度 | upstream backend {
ip_hash;
server backend1.example.com;
server backend2.example.com;
} |
缓存
| 语法 | 说明 | 示例 |
|---|
proxy_cache_path | 定义缓存路径和配置 | proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off; |
proxy_cache | 启用缓存 | proxy_cache my_cache; |
proxy_cache_key | 定义缓存键 | proxy_cache_key "$scheme$request_method$host$request_uri"; |
proxy_cache_valid | 设置缓存有效期 | proxy_cache_valid 200 301 302 10m; |
安全
| 语法 | 说明 | 示例 |
|---|
limit_req | 限制请求速率 | limit_req zone=one burst=5 nodelay; |
limit_conn | 限制连接数 | limit_conn addr 10; |
ssl | 启用 SSL | server {
listen 443 ssl;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
} |
add_header | 添加 HTTP 响应头 | add_header Strict-Transport-Security "max-age=31536000; includeSubDomains"; |
日志
| 语法 | 说明 | 示例 |
|---|
access_log | 指定访问日志文件位置 | access_log /var/log/nginx/access.log combined; |
log_format | 定义日志格式 | log_format combined '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"'; |
限制与优化
| 语法 | 说明 | 示例 |
|---|
client_max_body_size | 限制客户端请求的最大体大小 | client_max_body_size 10m; |
server_tokens | 隐藏服务器版本信息 | server_tokens off; |
tcp_nodelay | 禁用 Nagle 算法,减少延迟 | tcp_nodelay on; |
常用示例
静态文件服务
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}
反向代理
server {
listen 80;
server_name example.com;
location /api {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
重定向
server {
listen 80;
server_name example.com;
location /old {
return 301 http://example.com/new;
}
location /old2 {
rewrite ^/old2/([a-z]+)$ /new/$1 permanent;
}
}
负载均衡
upstream backend {
least_conn;
server backend1.example.com;
server backend2.example.com;
}
server {
listen 80;
server_name example.com;
location /api {
proxy_pass http://backend;
proxy_set_header Host $host;
}
}
缓存
http {
proxy_cache_path /data/nginx/cache 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 /api {
proxy_cache my_cache;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 301 302 10m;
proxy_pass http://backend;
}
}
}
SSL 配置
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/priv哥key.pem;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
}
}
安全配置
server {
listen 80;
server_name example.com;
location /api {
limit_req zone=one burst=5 nodelay;
limit_conn addr 10;
proxy_pass http://backend;
proxy_set_header Host $host;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";
}
}
日志配置
http {
log_format custom '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/access.log custom;
}
}
性能优化
http {
sendfile on;
tcp_nodelay on;
client_max_body_size 10m;
server_tokens off;
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html index.htm;
}
}
}
进阶技巧
热备份与恢复
http {
upstream backend {
server backend1.example.com;
server backend2.example.com backup;
}
server {
listen 80;
server_name example.com;
location /api {
proxy_pass http://backend;
proxy_set_header Host $host;
}
}
}
动态内容缓存
http {
proxy_cache_path /data/nginx/cache 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 /api {
proxy_cache my_cache;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 301 302 10m;
proxy_pass http://backend;
add_header X-Proxy-Cache $upstream_cache_status;
}
}
}
跨域资源共享 (CORS)
server {
listen 80;
server_name example.com;
location /api {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
proxy_pass http://backend;
}
}
压缩配置
http {
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_vary on;
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html index.htm;
}
}
}
防止 DDoS 攻击
http {
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
server {
listen 80;
server_name example.com;
location / {
limit_req zone=one burst=5 nodelay;
root /var/www/html;
index index.html index.htm;
}
}
}
限制文件类型上传
server {
listen 80;
server_name example.com;
location /upload {
root /var/www/html;
valid_referers none blocked example.com;
if ($invalid_referer) {
return 403;
}
if ($request_method = POST) {
limit_except GET {
allow 192.168.1.0/24;
deny all;
}
}
client_max_body_size 10m;
}
}
动态服务器配置
http {
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
server_name example.com;
location /ws {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
}
}
}
限制 IP 访问
server {
listen 80;
server_name example.com;
allow 192.168.1.0/24;
deny all;
location / {
root /var/www/html;
index index.html index.htm;
}
}
限制请求方法
server {
listen 80;
server_name example.com;
if ($request_method !~ ^(GET|POST)$) {
return 405;
}
location / {
root /var/www/html;
index index.html index.htm;
}
}
标准化错误页面
server {
listen 80;
server_name example.com;
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /404.html {
internal;
root /var/www/html;
}
location = /50x.html {
internal;
root /var/www/html;
}
}
日志切割
# 使用 logrotate 切割日志
# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 nginx adm
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
在线工具推荐
配置 Nginx 时,遇到复杂的 cron 表达式、正则表达式或 JSON 数据,可以使用 Hey Cron 进行快速生成和验证。Hey Cron 提供了多种实用工具,包括:
- Cron 表达式生成器:中文描述秒转 cron 表达式
- 正则表达式生成器:帮助你快速生成正则表达式
- 中英互译:支持中文和英文的互译
- JSON 格式化:帮助你格式化和验证 JSON 数据
- Base64 编码解码:快速编码和解码 Base64 字符串
- 时间戳转换:方便地在时间戳和日期时间之间进行转换
- JWT 解析:帮助你解析 JWT 令牌
希望这些工具能提升你的开发效率,少走弯路。
到此这篇关于Nginx 配置速查手册:核心语法与实战案例详解的文章就介绍到这了,更多相关Nginx 配置速查手册内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
最新评论