这个 nginx 快速参考备忘单显示了它的常用命和配置使用清单。
入门
服务管理
1 2 3 4 5 6 7 8 9 10
| sudo systemctl status nginx sudo systemctl reload nginx sudo systemctl restart nginx
sudo nginx -t nginx nginx -s reload nginx -s stop nginx -s quit nginx -V
|
Docker 安装
1
| docker run --name some-nginx -v /some/content:/usr/share/nginx/html:ro -d nginx
|
简单代理
1 2 3 4 5
| location / { proxy_pass http://127.0.0.1:3000; proxy_redirect off; proxy_set_header Host $host; }
|
全局变量
变量 |
说明 |
$args |
这个变量等于请求行中的参数,同 $query_string |
$remote_port |
客户端的端口 |
$content_length |
请求头中的 Content-length 字段 |
$remote_user |
已经经过 Auth Basic Module 验证的用户名 |
$content_type |
请求头中的 Content-Type 字段 |
$request_filename |
当前请求的文件路径,由 root 或alias指令与URI请求生成 |
$document_root |
当前请求在 root 指令中指定的值 |
$scheme |
HTTP方法(如http,https) |
$host |
请求主机头字段,否则为服务器名称 |
$hostname |
主机名 |
$http_user_agent |
客户端agent 信息 |
$http_cookie |
客户端cookie 信息 |
$server_protocol |
请求使用的协议,通常是HTTP/1.0 或HTTP/1.1 |
$server_addr |
服务器地址,在完成一次系统调用后可以确定这个值 |
$server_name |
服务器名称 |
$server_port |
请求到达服务器的端口号 |
$limit_rate |
这个变量可以限制连接速率 |
$request_method |
客户端请求的动作,如 GET/POST |
$request_uri |
包含请求参数的原始URI,不包含主机名,如:/foo/bar.php?arg=baz |
$remote_addr |
客户端的IP地址 |
$uri |
不带请求参数的当前URI,$uri 不包含主机名,如 /foo/bar.html |
$document_uri |
与 $uri 相同 |
$nginx_version |
nginx 版本 |
更多全局变量查看官方文档
监听端口
1 2 3 4 5 6 7 8
| server { listen 80; listen 443 ssl; listen 443 ssl http2; listen [::]:80; listen [::]:80 ipv6only=on; }
|
域名 (server_name)
1 2 3 4 5 6 7 8 9 10 11 12
| server { server_name example.com; server_name example.com www.example.com; server_name *.example.com; server_name example.*; server_name ""; }
|
负载均衡(简单实例)
1 2 3 4 5
| upstream node_js { server 0.0.0.0:3000; server 0.0.0.0:4000; server 127.155.142.421; }
|
负载均衡(权重)
1 2 3 4
| upstream test { server localhost:8080 weight=9; server localhost:8081 weight=1; }
|
upstream ip_hash
{2}1 2 3 4 5
| upstream test { ip_hash; server localhost:8080; server localhost:8081; }
|
解决负载均衡 session
的问题
upstream fair
{2}1 2 3 4 5
| upstream backend { fair; server localhost:8080; server localhost:8081; }
|
响应时间短的优先分配
server 可选参数
:- |
:- |
weight |
访问权重数值越高,收到请求越多 |
fail_timeout |
指定的时间内必须提供响应 |
max_fails |
尝试失败服务器连接的最大次数 |
down |
标记一个服务器不再接受任何请求 |
backup |
有服务器宕机,标记的机器接收请求 |
配置示例
1 2 3 4 5 6 7
| upstream test { server 127.0.0.1:83 weight=9; server 127.0.0.1:83 weight=1; server 127.0.0.1:83 max_fails=3; server 127.0.0.1:83 weight=3 down; }
|
upstream url_hash
{2,3}1 2 3 4 5 6
| upstream backend { hash $request_uri; hash_method crc32; server localhost:8080; server localhost:8081; }
|
按访问url的hash结果来分配请求
upstream keepalive
{4}1 2 3 4 5
| upstream memcached_backend { server 127.0.0.1:11211; server 10.0.0.2:11211; keepalive 32; }
|
激活缓存以连接到上游服务器
子文件夹中的代理
{1,2}1 2 3 4 5 6 7
| location /folder/ { proxy_pass http://127.0.0.1:3000/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }
|
反向代理
基础
1 2 3 4 5 6 7 8 9 10
| server { listen 80; server_name example.com; location / { proxy_pass http://0.0.0.0:3000; } }
|
基础 + (upstream)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| upstream node_js { server 0.0.0.0:3000; }
server { listen 80; server_name example.com; location / { proxy_pass http://node_js; } }
|
升级连接(适用于支持 WebSockets 的应用程序)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| upstream node_js { server 0.0.0.0:3000; }
server { listen 80; server_name example.com; location / { proxy_pass http://node_js; proxy_redirect off; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; } }
|
适用于 Node.js、Streamlit、Jupyter 等
静态资源(传统 Web 服务器)
1 2 3 4 5 6 7 8 9 10 11 12 13
| server { listen 80; server_name example.com; root /path/to/website; location / { } location /images/ { } location /videos/ { root /www/media; } }
|
HTTPS 协议
大多数 SSL 选项取决于您的应用程序做什么或需要什么
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| server { listen 443 ssl http2; server_name example.com; ssl on;
ssl_certificate /path/to/cert.pem; ssl_certificate_key /path/to/privkey.pem;
ssl_stapling on; ssl_stapling_verify on; ssl_trusted_certificate /path/to/fullchain.pem;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_session_timeout 1d; ssl_session_cache shared:SSL:50m; add_header Strict-Transport-Security max-age=15768000; }
|
您可以使用 Let’s Encrypt 轻松保护您的网站/应用程序。去 lets-encrypt 获取更多信息
重定向(301永久)
将 <www.example.com> 重定向到 example.com
1 2 3 4 5
| server { listen 80; server_name www.example.com; return 301 http://example.com$request_uri; }
|
将 http 重定向到 https
1 2 3 4 5
| server { listen 80; server_name example.com; return 301 https://example.com$request_uri; }
|
重定向(302临时)
1 2 3 4 5
| server { listen 80; server_name yourdomain.com; return 302 http://otherdomain.com; }
|
永久重定向到 HTTPS 安全域
1 2 3 4 5
| server { listen 80; server_name yourdomain.com; return 301 https://$host$request_uri; }
|
重定向参数
:- |
:- |
permanent |
永久性重定向。日志中的状态码为 301 |
redirect |
临时重定向。日志中的状态码为 302 |
HTTP 请求端真实的IP
1 2 3
| location / { proxy_set_header X-Forwarded-For $remote_addr; }
|
示例
websocket 的代理 keepalive
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| upstream backend { server 127.0.0.1:3000; keepalive 5; }
server { server_name your_hostname.com; error_log /var/log/nginx/rocketchat.access.log; location / { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forward-For $proxy_add_x_forwarded_for; proxy_set_header X-Forward-Proto http; proxy_set_header X-Nginx-Proxy true; proxy_redirect off; } }
|
Apache 的反向代理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| server { server_name domain.tld;
access_log /log/domain.tld.access.log; error_log /log/domain.tld.error.log; root /var/www/domain.tld/htdocs;
location / { proxy_pass http://backend; } location ~* \.(ogg|ogv|svg|svgz|eot|otf|woff|woff2|ttf|m4a|mp4|ttf|rss|atom|jpe?g|gif|cur|heic|png|tiff|ico|zip|webm|mp3|aac|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf|swf|webp)$ { add_header "Access-Control-Allow-Origin" "*"; access_log off; log_not_found off; expires max; try_files $uri @fallback; } location @fallback { proxy_pass http://backend; } }
|
Gitlab 的反向代理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| server { listen 80; server_name git.example.cn; location / { proxy_pass http://localhost:3000; proxy_redirect off; proxy_set_header Host $host; client_max_body_size 10m; client_body_buffer_size 128k; proxy_connect_timeout 300; proxy_send_timeout 300; proxy_read_timeout 300; proxy_buffer_size 4k; proxy_buffers 4 32k; proxy_busy_buffers_size 64k; } }
|
重定向整个网站
1 2 3 4
| server { server_name old-site.com; return 301 $scheme://new-site.com$request_uri; }
|
重定向单页
1 2 3 4 5
| server { location = /oldpage.html { return 301 http://example.org/newpage.html; } }
|
重定向整个子路径
1 2 3
| location /old-site { rewrite ^/old-site/(.*) http://example.org/new-site/$1 permanent; }
|
负载均衡
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| upstream example { ip_hash; server 192.168.122.11:8081 ; server 127.0.0.1:82 weight=3; server 127.0.0.1:83 weight=3 down; server 127.0.0.1:84 weight=3; max_fails=3 fail_timeout=20s; server 127.0.0.1:85 weight=4; keepalive 32; } server { listen 80; server_name git.example.cn; location / { proxy_pass http://example; } }
|
内容缓存
允许浏览器基本上永久地缓存静态内容。 Nginx 将为您设置 Expires 和 Cache-Control 头信息
{3}1 2 3 4
| location /static { root /data; expires max; }
|
如果要求浏览器永远不会缓存响应(例如用于跟踪请求),请使用 -1
{3}1 2 3 4
| location = /empty.gif { empty_gif; expires -1; }
|
跨域问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| server { listen 80; server_name api.xxx.com; add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Credentials' 'true'; add_header 'Access-Control-Allow-Methods' 'GET,POST,HEAD';
location / { proxy_pass http://127.0.0.1:3000; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; } }
|
重定向 URI 来解决跨域问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| upstream test { server 127.0.0.1:8080; server localhost:8081; } server { listen 80; server_name api.xxx.com; location / { root html; index index.html index.htm; } location ^~/api/{ rewrite ^/api/(.*)$ /$1 break; proxy_pass http://test;
proxy_cookie_path /platfrom/ /;
proxy_pass_header Set-Cookie; } }
|
跳转到带 www 的域上面
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| server { listen 80; server_name www.wangchujiang.com; root /home/www/wabg/download; location / { try_files $uri $uri/ /index.html =404; } }
server { server_name wangchujiang.com; rewrite ^(.*) https://www.wangchujiang.com$1 permanent; }
|
代理转发
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| upstream server-api { server 127.0.0.1:3110; } upstream server-resource { server 127.0.0.1:3120; } server { listen 3111; server_name localhost; root /home/www/server-statics; location ^~/api/ { rewrite ^/(.*)$ /$1 break; proxy_pass http://server-api; } location ^~/captcha { rewrite ^/(.*)$ /$1 break; proxy_pass http://server-api; } location ^~/img/ { rewrite ^/(.*)$ /$1 break; proxy_pass http://server-resource; } location / { try_files $uri $uri/ /index.html =404; } }
|
屏蔽 IP
可以放到 http
, server
, location
, limit_except
语句块
在 blockip.conf
里面输入内容,如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| deny 165.91.122.67;
deny IP; allow IP; deny all; allow all; deny 123.0.0.0/8; deny 124.45.0.0/16; deny 123.45.6.0/24;
allow 1.1.1.1; allow 1.1.1.2; deny all;
|
强制将 http 重定向到 https
1 2 3 4 5 6 7
| server { listen 80; server_name example.com; rewrite ^ https://$http_host$request_uri? permanent; server_tokens off; }
|
代理转发连接替换
1 2 3 4
| location ^~/api/upload { rewrite ^/(.*)$ /wfs/v1/upload break; proxy_pass http://wfs-api; }
|
将地址 /api/upload
替换为 /wfs/v1/upload
爬虫 User-Agent 过滤
1 2 3 4 5 6 7
| location / { if ($http_user_agent ~* "python|curl|java|wget|httpclient|okhttp") { return 503; } }
|
图片防盗链
1 2 3 4 5 6 7 8 9 10
| location ~* \.(gif|jpg|png|swf|flv)$ { root html;
valid_referers none blocked *.nginx.com;
if ($invalid_referer) { rewrite ^/ www.nginx.cn; } }
|
虚拟目录配置
1 2 3 4 5 6 7 8 9 10
| location /img/ { alias /var/www/image/; }
location /img/ { root /var/www/image; }
|
屏蔽文件目录
通用备份和归档文件
1 2 3
| location ~* "\.(old|orig|original|php#|php~|php_bak|save|swo|aspx?|tpl|sh|bash|bak?|cfg|cgi|dll|exe|git|hg|ini|jsp|log|mdb|out|sql|svn|swp|tar|rdf)$" { deny all; }
|
拒绝访问 .git
和 .svn
目录
1 2 3
| location ~ (.git|.svn) { deny all; }
|
拒绝访问隐藏文件和目录
1 2 3
| location ~ /\.(?!well-known\/) { deny all; }
|
防盗图配置
1 2 3 4 5 6
| location ~ \/public\/(css|js|img)\/.*\.(js|css|gif|jpg|jpeg|png|bmp|swf) { valid_referers none blocked *.jslite.io; if ($invalid_referer) { rewrite ^/ http://wangchujiang.com/piratesp.png; } }
|
ulimit 不继承系统设置的问题
解决 systemctl
管理的 ulimit 不继承系统设置的问题
Gzip 配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| gzip on; gzip_buffers 16 8k; gzip_comp_level 6; gzip_http_version 1.1; gzip_min_length 256; gzip_proxied any; gzip_vary on; gzip_types text/xml application/xml application/atom+xml application/rss+xml application/xhtml+xml image/svg+xml text/javascript application/javascript application/x-javascript text/x-json application/json application/x-web-app-manifest+json text/css text/plain text/x-component font/opentype application/x-font-ttf application/vnd.ms-fontobject image/x-icon; gzip_disable "msie6";
|
阻止常见攻击
base64编码的网址
1 2 3
| location ~* "(base64_encode)(.*)(\()" { deny all; }
|
javascript eval() url
1 2 3
| location ~* "(eval\()" { deny all; }
|
使网站不可索引
1 2 3 4 5
| add_header X-Robots-Tag "noindex";
location = /robots.txt { return 200 "User-agent: *\nDisallow: /\n"; }
|
另见