nginx 代理

#options请求直接204
if ($request_method = 'OPTIONS') {
        # 对于OPTIONS,不保存请求日志到日志文件
        access_log off;

        # 这里配置允许跨域的域名,* 代表所有,也可以写域名:http://www.xxx.com 或者IP+端口 http://192.168.1.10
        add_header 'Access-Control-Allow-Origin' '*';
        # 允许的请求类型
        add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
        add_header 'Access-Control-Allow-Credentials' true;
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
        # 允许跨域的最大时间,超过这个时间又会重发一次OPTIONS请求获取新的认证
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain charset=UTF-8';
        add_header 'Content-Length' 0;
        # 直接在这里返回204响应,不转发到后台服务程序
        return 204;
 }
#接口重定向
location /api/ {
            #如果浏览器访问正常 而nginx 504 把 $host 改成固定的域名 如下面的 localhost
			proxy_connect_timeout   10s; 
            proxy_send_timeout      10s; 
            proxy_read_timeout      10s; 
			proxy_set_header Host $host;
			proxy_set_header X-Real-IP $remote_addr;
			proxy_set_header REMOTE-HOST $remote_addr;
			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_pass http://localhost:8080/;
}
		
#ws重定向
#参考 https://zhuanlan.zhihu.com/p/383598729 proxy_read_timeout proxy_write_timeout 需要特别注意
location /socket/ {
      proxy_read_timeout     7200s; #尽量设置均等。超时会导致websocket自动关闭
      proxy_http_version      1.1;
      proxy_set_header        Upgrade         $http_upgrade;
      proxy_set_header        Connection      "$connection_upgrade";
      proxy_pass              http://localhost:8080/socket/;
}
#connection_upgrade变量要在server{外 添加 
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
   }
posted @ 2022-09-26 10:22  狂客  阅读(71)  评论(0编辑  收藏  举报