Nginx反向代理与负载均衡配置

1、反向代理配置:

server {
   #监听端口号
   listen       8888; 
   
   #监听地址:服务器地址或绑定的域名,多个名称之间用空格隔开
   #可以使用通配符“*”,但通配符只能用在首段或者尾端
   server_name  api.xxx.cn api.abc.com *.123.com www.123.*; 

   #charset koi8-r;

   #access_log  logs/host.access.log  main;

   #匹配URL
   #1、= :用于不含正则表达式的 uri 前,要求请求字符串与 uri 严格匹配,如果匹配成功,就停止继续向下搜索并立即处理该请求。
  #2、~:用于表示 uri 包含正则表达式,并且区分大小写。
  #3、~*:用于表示 uri 包含正则表达式,并且不区分大小写。
  #4、^~:用于不含正则表达式的 uri 前,要求 Nginx 服务器找到标识 uri 和请求字符串匹配度最高的 location 后,立即使用此 location 处理请求,而不再使用 location 块中的正则 uri 和请求字符串做匹配。
  #5、如果 uri 包含正则表达式,则必须要有 ~ 或者 ~* 标识。
   #6、 ^~/api 表示匹配前缀为api的请求
   #location [ = | ~ | ~* | ^~] uri 
   
   location / {
   	   #代理目标地址
       proxy_pass http://192.168.3.3:800;
       index  index.html index.htm;
       proxy_set_header Host $host;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
       proxy_set_header REMOTE-HOST $remote_addr;
       add_header X-Cache $upstream_cache_status;
       add_header Cache-Control no-cache;
   }

   #error_page  404              /404.html;

   # redirect server error pages to the static page /50x.html
   #
   error_page   500 502 503 504  /50x.html;
   location = /50x.html {
       root   html;
   }


   # deny access to .htaccess files, if Apache's document root
   # concurs with nginx's one
   #
   #location ~ /\.ht {
   #    deny  all;
   #}
}

2、负载均衡

# 负载均衡
upstream dispense {
   server nacos1:8848 weight=1;
   server nacos2:8848 weight=1;
}

# nacos TCP转发,不必添加网上所说的–with-stream,Docker-compose安装完Nginx之后默认支持stream
stream {
   upstream nacos-server-grpc9848 {
     hash $remote_addr consistent;
     server nacos1:9848 weight=1 max_fails=3 fail_timeout=10s;
     server nacos2:9848 weight=1 max_fails=3 fail_timeout=10s;
  }

  server {
     listen 9848 so_keepalive=on;
     proxy_connect_timeout 5s;
     proxy_timeout 5s;
     proxy_pass nacos-server-grpc9848;
  }

  upstream nacos-server-grpc9849 {
    hash $remote_addr consistent;
    server nacos1:9849 weight=1 max_fails=3 fail_timeout=10s;
    server nacos2:9849 weight=1 max_fails=3 fail_timeout=10s;
  }

  server {
     listen 9849 so_keepalive=on;
     proxy_connect_timeout 20s;
     proxy_timeout 5m;
     #proxy_pass nacos-server-grpc9849;
  }   
}

3、URL重写

server {
  listen       80;
  server_name  cellphone-mate.net;
  rewrite ^/(.*) http://www.abc-mate.net/$1 permanent; 
}

 

posted @ 2021-12-20 11:26  滔天蟹  阅读(230)  评论(0)    收藏  举报