nginx 配置总结

2.21'23

介绍

Nginx 是服务端软件,可以实现 API 网关、反向代理、微服务和负载均衡等。

Firewall

配置好 Nginx 后,可能因为防火墙导致无法访问

使用 UFW (Ubuntu, Debian)

ufw allow 'Nginx Full'

# OR
ufw allow 80/tcp
ufw allow 443/tcp

git server: 413 error

client_max_body_size 50m;

Default: client_max_body_size 1m;

http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size

Limiting Access

可以限制每个 IP 的连接数、请求频率、下载速度等。

NGINX Docs | Limiting Access to Proxied HTTP Resources

举例:限制每秒或每分钟的最大请求次数 (1r/s, 60r/m)

http {
    #...
    limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;

    server {
        #...
        location /search/ {
            limit_req zone=one;
            limit_req_status 429;
        }
    }
}

负载均衡

Using nginx as HTTP load balance

根据特定算法,将请求转发到多个服务器组成的集群中。以提高性能、可扩展性和可用性。

http {
    upstream myapp1 {
        ip_hash;
        server srv1.example.com;
        server srv2.example.com;
        server srv3.example.com;
    }

    server {
        listen 80;

        location / {
            proxy_pass http://myapp1;
        }
    }
}

设置访问日志 access_log

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;

查看访问日志

tail -f /var/log/nginx/access.log | grep 404

代理 react 打包后的静态网站,避免子路径 404

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

代理 websocket

需要额外做些配置,以支持 socket 连接

location / {
    proxy_pass http://localhost:8080;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
}

启动 gzip 压缩

nginx 可以使用 gzip 压缩响应数据,通过网络传给浏览器解压后使用,可以极大降低传输时间。

gzip on; # 开启
gzip_types \*; # 默认仅压缩 text/html

静态资源(图片等)配置缓存

Cache-Control 参考

location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    expires 2d;
    add_header Cache-Control "public, no-transform";
}

重启

nginx -s reload

加载其它配置文件

include /path/to/*.conf

端口转发配置

一般默认访问端口为 http: 80,https: 443。现在需要转到 5001 端口(通常 Web 应用都会有一个自定义的端口)。

/etc/nginx/nginx/conf

转发到特定端口

location / {
    proxy_pass http://127.0.0.1:5001;
}

先静态文件,然后再到特定端口

location / {
    root /path/to/static;
    try_files $uri @mysite;

    expires max;
    access_log off;
}

location @mysite {
    proxy_pass http://127.0.0.1:5001;
}

不生效解决办法:去掉 root 行

默认配置文件中可能包含了 root ,导致直接打开了 html。需要注释掉这一行以便转发生效。

# root         /usr/share/nginx/html;
📖