参考资料

  1. nginx 配置静态资源
  2. Nginxallow、deny:IP访问控制模块详细说明以及案例
  3. Nginx静态资源服务器搭建详细说明以及案例
  4. Nginxserver_name 配置主机名称详细说明以及案例
  5. Nginxalias 访问路径别名指令详细说明以及案例
  6. Nginx配置修改工具Ansible详细说明以及案例
  7. NginxWeb缓存配置详细说明以及案例
  8. Nginx gRPC代理服务器详细说明以及案例

nginx反向代理配置详解

  1. 基础配置


  1. server {
  2.     listen 80;
  3.     server_name example.com;
  4.     location / {
  5.         proxy_pass http://backend_server;
  6.         proxy_set_header Host $host;
  7.         proxy_set_header X-Real-IP $remote_addr;
  8.         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  9.     }
  10. }
  • listen: 监听端口

  • server_name: 域名或IP

  • location: 匹配请求路径

  • proxy_pass: 指定后端服务地址

  • proxy_set_header: 设置请求头传递信息

  1. 常用参数

  • proxy_connect_timeout: 后端连接超时时间(默认60s)

  • proxy_read_timeout: 读取后端响应超时时间(默认60s)

  • proxy_send_timeout: 发送请求到后端的超时时间(默认60s)

  • proxy_buffering off: 关闭响应缓冲(适用于实时流)

  1. SSL配置


  1. server {
  2.     listen 443 ssl;
  3.     server_name example.com;
  4.     ssl_certificate /path/to/cert.pem;
  5.     ssl_certificate_key /path/to/key.pem;
  6.     location / {
  7.         proxy_pass http://backend_server;
  8.         # 保持基础配置中的header设置
  9.     }
  10. }
  1. WebSocket支持


  1. location /ws/ {
  2.     proxy_pass http://websocket_server;
  3.     proxy_http_version 1.1;
  4.     proxy_set_header Upgrade $http_upgrade;
  5.     proxy_set_header Connection "upgrade";
  6. }
  1. 负载均衡


  1. upstream backend {
  2.     server 192.168.1.10:8080;
  3.     server 192.168.1.11:8080;
  4.     server 192.168.1.12:8080;
  5. }
  6. server {
  7.     location / {
  8.         proxy_pass http://backend;
  9.     }
  10. }
  1. 缓存控制


  1. proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m;
  2. location / {
  3.     proxy_cache my_cache;
  4.     proxy_cache_valid 200 302 10m;
  5.     proxy_cache_valid 404      1m;
  6. }

检查配置并重载


  1. nginx -t        # 验证配置
  2. nginx -s reload # 重载配置
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐