NGINX 备忘清单

这个 nginx 快速参考备忘单显示了它的常用命和配置使用清单。

入门

服务管理

  1. sudo systemctl status nginx # nginx当前状态
  2. sudo systemctl reload nginx # 重新加载 nginx
  3. sudo systemctl restart nginx # 重启nginx
  4. sudo nginx -t # 检查语法
  5. nginx # 启动
  6. nginx -s reload # 重启
  7. nginx -s stop # 关闭进程
  8. nginx -s quit # 平滑关闭nginx
  9. nginx -V # 查看nginx的安装状态,

Docker 安装

  1. docker run --name some-nginx -v /some/content:/usr/share/nginx/html:ro -d nginx

简单代理

  1. location / {
  2. proxy_pass http://127.0.0.1:3000;
  3. proxy_redirect off;
  4. proxy_set_header Host $host;
  5. }

全局变量

变量 说明
$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.0HTTP/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. server {
  2. listen 80; # 标准 HTTP 协议
  3. listen 443 ssl; # 标准 HTTPS 协议
  4. listen 443 ssl http2; # 对于 http2
  5. listen [::]:80; # 使用 IPv6 在 80 上收听
  6. # 仅收听使用 IPv6
  7. listen [::]:80 ipv6only=on;
  8. }

域名 (server_name)

  1. server {
  2. # 监听 example.com
  3. server_name example.com;
  4. # 监听多个域
  5. server_name example.com www.example.com;
  6. # 监听所有子域
  7. server_name *.example.com;
  8. # 监听所有顶级域
  9. server_name example.*;
  10. # 监听未指定的主机名(监听 IP 地址本身)
  11. server_name "";
  12. }

负载均衡(简单实例)

  1. upstream node_js {
  2. server 0.0.0.0:3000;
  3. server 0.0.0.0:4000;
  4. server 127.155.142.421;
  5. }

负载均衡(权重)

  1. upstream test {
  2. server localhost:8080 weight=9;
  3. server localhost:8081 weight=1;
  4. }

upstream ip_hash

```nginx {2} upstream test { ip_hash; server localhost:8080; server localhost:8081; }

  1. 解决负载均衡 `session` 的问题
  2. ### upstream fair
  3. ```nginx {2}
  4. upstream backend {
  5. fair;
  6. server localhost:8080;
  7. server localhost:8081;
  8. }

响应时间短的优先分配

server 可选参数

:- :-
weight 访问权重数值越高,收到请求越多
fail_timeout 指定的时间内必须提供响应
max_fails 尝试失败服务器连接的最大次数
down 标记一个服务器不再接受任何请求
backup 有服务器宕机,标记的机器接收请求

配置示例

  1. upstream test {
  2. server 127.0.0.1:83 weight=9; # 权重
  3. server 127.0.0.1:83 weight=1; # 权重
  4. # 失败超时时间
  5. server 127.0.0.1:83 max_fails=3;
  6. server 127.0.0.1:83 weight=3 down;
  7. }

upstream url_hash

```nginx {2,3} upstream backend { hash $request_uri; hash_method crc32; server localhost:8080; server localhost:8081; }

  1. 按访问urlhash结果来分配请求
  2. ### upstream keepalive
  3. ```nginx {4}
  4. upstream memcached_backend {
  5. server 127.0.0.1:11211;
  6. server 10.0.0.2:11211;
  7. keepalive 32;
  8. }

激活缓存以连接到上游服务器

子文件夹中的代理

```nginx {1,2} 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. <!--rehype:wrap-class=row-span-3-->
  3. #### 基础
  4. ```nginx
  5. server {
  6. listen 80;
  7. server_name example.com;
  8. location / {
  9. proxy_pass http://0.0.0.0:3000;
  10. # 其中 0.0.0.0:3000 是绑定在
  11. # 0.0.0.0端口3000 列表上的 Node.js 服务器
  12. }
  13. }

基础 + (upstream)

  1. upstream node_js {
  2. server 0.0.0.0:3000;
  3. # 其中 0.0.0.0:3000 是绑定在
  4. # 0.0.0.0端口3000 列表上的 Node.js 服务器
  5. }
  6. server {
  7. listen 80;
  8. server_name example.com;
  9. location / {
  10. proxy_pass http://node_js;
  11. }
  12. }

升级连接(适用于支持 WebSockets 的应用程序)

  1. upstream node_js {
  2. server 0.0.0.0:3000;
  3. }
  4. server {
  5. listen 80;
  6. server_name example.com;
  7. location / {
  8. proxy_pass http://node_js;
  9. proxy_redirect off;
  10. proxy_http_version 1.1;
  11. proxy_set_header Upgrade $http_upgrade;
  12. proxy_set_header Connection "upgrade";
  13. proxy_set_header Host $host;
  14. }
  15. }

适用于 Node.js、Streamlit、Jupyter 等

静态资源(传统 Web 服务器)

  1. server {
  2. listen 80;
  3. server_name example.com;
  4. root /path/to/website;
  5. # root /www/data/ 示例,如果里面没有'root',它将寻找 /www/data/index.html
  6. location / {
  7. }
  8. location /images/ { # 如果里面没有“root”,它将寻找 /www/data/images/index.html
  9. }
  10. location /videos/ { # 由于里面有“root”,它会寻找 /www/media/videos/index.html
  11. root /www/media;
  12. }
  13. }

HTTPS 协议

大多数 SSL 选项取决于您的应用程序做什么或需要什么

  1. server {
  2. listen 443 ssl http2;
  3. server_name example.com;
  4. ssl on;
  5. ssl_certificate /path/to/cert.pem;
  6. ssl_certificate_key /path/to/privkey.pem;
  7. ssl_stapling on;
  8. ssl_stapling_verify on;
  9. ssl_trusted_certificate /path/to/fullchain.pem;
  10. ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
  11. ssl_session_timeout 1d;
  12. ssl_session_cache shared:SSL:50m;
  13. add_header Strict-Transport-Security max-age=15768000;
  14. }

您可以使用 Let’s Encrypt 轻松保护您的网站/应用程序。去 lets-encrypt 获取更多信息

重定向(301永久)

将 www.example.com 重定向到 example.com

  1. server {
  2. listen 80;
  3. server_name www.example.com;
  4. return 301 http://example.com$request_uri;
  5. }

将 http 重定向到 https

  1. server {
  2. listen 80;
  3. server_name example.com;
  4. return 301 https://example.com$request_uri;
  5. }

重定向(302临时)

  1. server {
  2. listen 80;
  3. server_name yourdomain.com;
  4. return 302 http://otherdomain.com;
  5. }

永久重定向到 HTTPS 安全域

  1. server {
  2. listen 80;
  3. server_name yourdomain.com;
  4. return 301 https://$host$request_uri;
  5. }

重定向参数

:- :-
permanent 永久性重定向。日志中的状态码为 301
redirect 临时重定向。日志中的状态码为 302

HTTP 请求端真实的IP

  1. location / {
  2. proxy_set_header X-Forwarded-For $remote_addr;
  3. }

示例

websocket 的代理 keepalive

  1. # Upstreams
  2. upstream backend {
  3. server 127.0.0.1:3000;
  4. keepalive 5;
  5. }
  6. # HTTP Server
  7. server {
  8. server_name your_hostname.com;
  9. error_log /var/log/nginx/rocketchat.access.log;
  10. location / {
  11. proxy_pass http://backend;
  12. proxy_http_version 1.1;
  13. proxy_set_header Upgrade $http_upgrade;
  14. proxy_set_header Connection "upgrade";
  15. proxy_set_header Host $http_host;
  16. proxy_set_header X-Real-IP $remote_addr;
  17. proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
  18. proxy_set_header X-Forward-Proto http;
  19. proxy_set_header X-Nginx-Proxy true;
  20. proxy_redirect off;
  21. }
  22. }

Apache 的反向代理

  1. server {
  2. server_name domain.tld;
  3. access_log /log/domain.tld.access.log;
  4. error_log /log/domain.tld.error.log;
  5. root /var/www/domain.tld/htdocs;
  6. # 将请求传递给 Apache 后端
  7. location / {
  8. proxy_pass http://backend;
  9. }
  10. # 使用后备处理静态文件
  11. 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)$ {
  12. add_header "Access-Control-Allow-Origin" "*";
  13. access_log off;
  14. log_not_found off;
  15. expires max;
  16. try_files $uri @fallback;
  17. }
  18. # 如果找不到文件,则回退以将请求传递给 Apache
  19. location @fallback {
  20. proxy_pass http://backend;
  21. }
  22. }

Gitlab 的反向代理

  1. server {
  2. #侦听的80端口
  3. listen 80;
  4. server_name git.example.cn;
  5. location / {
  6. proxy_pass http://localhost:3000;
  7. # 以下是一些反向代理的配置可删除
  8. proxy_redirect off;
  9. # 后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
  10. proxy_set_header Host $host;
  11. client_max_body_size 10m; # 允许客户端请求的最大单文件字节数
  12. client_body_buffer_size 128k; # 缓冲区代理缓冲用户端请求的最大字节数
  13. proxy_connect_timeout 300; # nginx跟后端服务器连接超时时间(代理连接超时)
  14. proxy_send_timeout 300; # 后端服务器数据回传时间(代理发送超时)
  15. proxy_read_timeout 300; # 连接成功后,后端服务器响应时间(代理接收超时)
  16. # 设置代理服务器(nginx)保存用户头信息的缓冲区大小
  17. proxy_buffer_size 4k;
  18. # proxy_buffers缓冲区,网页平均在32k以下的话,这样设置
  19. proxy_buffers 4 32k;
  20. # 高负荷下缓冲大小(proxy_buffers*2)
  21. proxy_busy_buffers_size 64k;
  22. }
  23. }

重定向整个网站

  1. server {
  2. server_name old-site.com;
  3. return 301 $scheme://new-site.com$request_uri;
  4. }

重定向单页

  1. server {
  2. location = /oldpage.html {
  3. return 301 http://example.org/newpage.html;
  4. }
  5. }

重定向整个子路径

  1. location /old-site {
  2. rewrite ^/old-site/(.*) http://example.org/new-site/$1 permanent;
  3. }

负载均衡

  1. upstream example {
  2. ip_hash;
  3. # upstream的负载均衡,weight是权重,可以根据机器配置定义权重。
  4. # weigth参数表示权值,权值越高被分配到的几率越大。
  5. server 192.168.122.11:8081 ;
  6. server 127.0.0.1:82 weight=3;
  7. server 127.0.0.1:83 weight=3 down;
  8. server 127.0.0.1:84 weight=3; max_fails=3 fail_timeout=20s;
  9. server 127.0.0.1:85 weight=4;;
  10. keepalive 32;
  11. }
  12. server {
  13. #侦听的80端口
  14. listen 80;
  15. server_name git.example.cn;
  16. location / {
  17. # 在这里设置一个代理,和 upstream 的名字一样
  18. proxy_pass http://example;
  19. }
  20. }

内容缓存

允许浏览器基本上永久地缓存静态内容。 Nginx 将为您设置 Expires 和 Cache-Control 头信息

```nginx {3} location /static { root /data; expires max; }

  1. 如果要求浏览器永远不会缓存响应(例如用于跟踪请求),请使用 `-1`
  2. ```nginx {3}
  3. location = /empty.gif {
  4. empty_gif;
  5. expires -1;
  6. }

跨域问题

  1. server {
  2. listen 80;
  3. server_name api.xxx.com;
  4. add_header 'Access-Control-Allow-Origin' '*';
  5. add_header 'Access-Control-Allow-Credentials' 'true';
  6. add_header 'Access-Control-Allow-Methods' 'GET,POST,HEAD';
  7. location / {
  8. proxy_pass http://127.0.0.1:3000;
  9. proxy_set_header X-Real-IP $remote_addr;
  10. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  11. proxy_set_header Host $http_host;
  12. }
  13. }

重定向 URI 来解决跨域问题

  1. upstream test {
  2. server 127.0.0.1:8080;
  3. server localhost:8081;
  4. }
  5. server {
  6. listen 80;
  7. server_name api.xxx.com;
  8. location / {
  9. root html; # 去请求../html文件夹里的文件
  10. index index.html index.htm; # 首页响应地址
  11. }
  12. # 用于拦截请求,匹配任何以 /api/开头的地址,
  13. # 匹配符合以后,停止往下搜索正则。
  14. location ^~/api/{
  15. # 代表重写拦截进来的请求,并且只能对域名后边的除去传递的参数外的字符串起作用
  16. # 例如www.a.com/api/msg?meth=1&par=2重写,只对/api/msg重写。
  17. # rewrite后面的参数是一个简单的正则 ^/api/(.*)$,
  18. # $1代表正则中的第一个(),$2代表第二个()的值,以此类推。
  19. rewrite ^/api/(.*)$ /$1 break;
  20. # 把请求代理到其他主机
  21. # 其中 http://www.b.com/ 写法和 http://www.b.com写法的区别如下
  22. # 如果你的请求地址是他 http://server/html/test.jsp
  23. # 配置一: http://www.b.com/ 后面有“/”
  24. # 将反向代理成 http://www.b.com/html/test.jsp 访问
  25. # 配置一: http://www.b.com 后面没有有“/”
  26. # 将反向代理成 http://www.b.com/test.jsp 访问
  27. proxy_pass http://test;
  28. # 如果 proxy_pass URL 是 http://a.xx.com/platform/ 这种情况
  29. # proxy_cookie_path应该设置成 /platform/ / (注意两个斜杠之间有空格)。
  30. proxy_cookie_path /platfrom/ /;
  31. # 设置 Cookie 头通过
  32. proxy_pass_header Set-Cookie;
  33. }
  34. }

跳转到带 www 的域上面

  1. server {
  2. listen 80;
  3. # 配置正常的带www的域名
  4. server_name www.wangchujiang.com;
  5. root /home/www/wabg/download;
  6. location / {
  7. try_files $uri $uri/ /index.html =404;
  8. }
  9. }
  10. server {
  11. # 将不带 www 的 wangchujiang.com
  12. # 永久性重定向到 https://www.wangchujiang.com
  13. server_name wangchujiang.com;
  14. rewrite ^(.*) https://www.wangchujiang.com$1 permanent;
  15. }

代理转发

  1. upstream server-api {
  2. # api 代理服务地址
  3. server 127.0.0.1:3110;
  4. }
  5. upstream server-resource {
  6. # 静态资源 代理服务地址
  7. server 127.0.0.1:3120;
  8. }
  9. server {
  10. listen 3111;
  11. server_name localhost; # 这里指定域名
  12. root /home/www/server-statics;
  13. # 匹配 api 路由的反向代理到API服务
  14. location ^~/api/ {
  15. rewrite ^/(.*)$ /$1 break;
  16. proxy_pass http://server-api;
  17. }
  18. # 假设这里验证码也在API服务中
  19. location ^~/captcha {
  20. rewrite ^/(.*)$ /$1 break;
  21. proxy_pass http://server-api;
  22. }
  23. # 假设你的图片资源全部在另外一个服务上面
  24. location ^~/img/ {
  25. rewrite ^/(.*)$ /$1 break;
  26. proxy_pass http://server-resource;
  27. }
  28. # 路由在前端,后端没有真实路由,
  29. # 路由不存在的 404 状态的页面返回 /index.html
  30. # 使用场景,用在 React/Vue项目没有真实路由
  31. location / {
  32. try_files $uri $uri/ /index.html =404;
  33. # 空格很重要 ^
  34. }
  35. }

屏蔽 IP

可以放到 http, server, location, limit_except 语句块

  1. include blockip.conf;

blockip.conf 里面输入内容,如:

  1. deny 165.91.122.67;
  2. deny IP; # 屏蔽单个 ip 访问
  3. allow IP; # 允许单个 ip 访问
  4. deny all; # 屏蔽所有 ip 访问
  5. allow all; # 允许所有 ip 访问
  6. deny 123.0.0.0/8; # 屏蔽整个段即从 123.0.0.1 到 123.255.255.254 访问的命令
  7. deny 124.45.0.0/16; # 屏蔽IP段即从 123.45.0.1 到 123.45.255.254 访问的命令
  8. deny 123.45.6.0/24; # 屏蔽IP段即从 123.45.6.1 到 123.45.6.254 访问的命令
  9. # 如果你想实现这样的应用,除了几个IP外,其他全部拒绝
  10. allow 1.1.1.1;
  11. allow 1.1.1.2;
  12. deny all;

强制将 http 重定向到 https

  1. server {
  2. listen 80;
  3. server_name example.com;
  4. rewrite ^ https://$http_host$request_uri? permanent; # 强制将 http 重定向到 https
  5. # 在错误页面和“服务器”响应头字段中启用或禁用发射nginx版本。 防止黑客利用版本漏洞攻击
  6. server_tokens off;
  7. }

代理转发连接替换

  1. location ^~/api/upload {
  2. rewrite ^/(.*)$ /wfs/v1/upload break;
  3. proxy_pass http://wfs-api;
  4. }

将地址 /api/upload 替换为 /wfs/v1/upload

爬虫 User-Agent 过滤

  1. location / {
  2. if ($http_user_agent ~* "python|curl|java|wget|httpclient|okhttp") {
  3. return 503;
  4. }
  5. # 正常处理
  6. # ...
  7. }

图片防盗链

  1. location ~* \.(gif|jpg|png|swf|flv)$ {
  2. root html;
  3. valid_referers none blocked *.nginx.com;
  4. if ($invalid_referer) {
  5. rewrite ^/ www.nginx.cn;
  6. # return 404;
  7. }
  8. }

虚拟目录配置

  1. location /img/ {
  2. alias /var/www/image/;
  3. }
  4. # 访问 /img/ 目录里面的文件时,
  5. # 会自动去 /var/www/image/ 目录找文件
  6. location /img/ {
  7. root /var/www/image;
  8. }
  9. # 访问 /img/ 目录下的文件时,
  10. # 会去 /var/www/image/img/ 目录下找文件

屏蔽文件目录

通用备份和归档文件

  1. 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)$" {
  2. deny all;
  3. }

拒绝访问 .git.svn 目录

  1. location ~ (.git|.svn) {
  2. deny all;
  3. }

拒绝访问隐藏文件和目录

  1. location ~ /\.(?!well-known\/) {
  2. deny all;
  3. }

防盗图配置

  1. location ~ \/public\/(css|js|img)\/.*\.(js|css|gif|jpg|jpeg|png|bmp|swf) {
  2. valid_referers none blocked *.jslite.io;
  3. if ($invalid_referer) {
  4. rewrite ^/ http://wangchujiang.com/piratesp.png;
  5. }
  6. }

阻止常见攻击

base64编码的网址

  1. location ~* "(base64_encode)(.*)(\()" {
  2. deny all;
  3. }

javascript eval() url

  1. location ~* "(eval\()" {
  2. deny all;
  3. }

Gzip 配置

  1. gzip on;
  2. gzip_buffers 16 8k;
  3. gzip_comp_level 6;
  4. gzip_http_version 1.1;
  5. gzip_min_length 256;
  6. gzip_proxied any;
  7. gzip_vary on;
  8. gzip_types
  9. text/xml application/xml application/atom+xml application/rss+xml application/xhtml+xml image/svg+xml
  10. text/javascript application/javascript application/x-javascript
  11. text/x-json application/json application/x-web-app-manifest+json
  12. text/css text/plain text/x-component
  13. font/opentype application/x-font-ttf application/vnd.ms-fontobject
  14. image/x-icon;
  15. gzip_disable "msie6";

使网站不可索引

  1. add_header X-Robots-Tag "noindex";
  2. location = /robots.txt {
  3. return 200 "User-agent: *\nDisallow: /\n";
  4. }

另见