Nginx跨域设置

  参考:https://www.cnblogs.com/bninp/p/5694277.html

  当出现403跨域错误的时候 No 'Access-Control-Allow-Origin' header is present on the requested resource,需要给Nginx服务器配置响应的header参数:

  在Nginx配置的location下添加以下配置

add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
add_header Access-Control-Allow-Credentials: true;
add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
     

  PS:1,Access-Control-Allow-Origin允许跨域的源 * 代表允许所有,可以使用"http://域名"配置

     2,需要在最终的目的Nginx配置,而不能在反向代理的Nginx配置

 2024-10-14补充开始

设置跨域后在前端请求不生效返回405 nginx日志信息如下

{"time_local": "14/Oct/2024:15:17:35 +0800", "remote_addr": "1.1.1.1", "request_uri": "/v1/chat/completions", "request_length": "545", "request_time": "0.001", "request_method": "OPTIONS", "status": "405", "body_bytes_sent": "31", "http_referer": "https://wb-baidu.cloud.com/", "http_user_agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36", "http_x_forwarded_for": "", "http_host": "edu.cloud.com", "server_name": "edu.cloud.com", "upstream": "192.168.3.26:8004", "upstream_response_time": "0.002", "upstream_status": "405", }

发现从前端发过来的请求方法是OPTIONS而不是POST

解决方法

修改配置文件在location增加以下配置加一个判断

if ($request_method = OPTIONS ) {
               add_header 'Access-Control-Allow-Origin' '*' always;
               add_header 'Access-Control-Allow-Methods' '*';
               add_header 'Access-Control-Allow-Headers' '*';
               add_header 'Access-Control-Allow-Credentials' 'true';
               return 200;
             }

整体配置如下

2024-10-14补充结束

posted @ 2019-03-16 08:48  minseo  阅读(480)  评论(0编辑  收藏  举报