宝塔用户_qgqjfh 发表于 2024-4-17 17:25:48

【已完成】允许Cors跨域访问,配置文件报错。

允许Cors跨域访问,配置文件报错。如下图:

我是这样配置的,



代码如下:
    #SSL-END
#配置允许baidu.com的Cors请求1
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
if ($request_method = 'OPTIONS') {
    return 204;
}

#配置允许baidu.com的Cors请求2
if ($http_origin ~* (https?://baidu.com(:+)?$)) {
    add_header 'Access-Control-Allow-Origin' "$http_origin";
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
    }


堡塔运维南一 发表于 2024-4-17 17:46:07

您好,报错显示您的语法不正确,请您检查一下
这个是配置 Nginx 以允许来自任何源的跨域请求:,参考一下
server {
    listen 80;
    server_name your.domain.com;

    location / {
      # 允许来自任何域的请求
      if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Allow-Origin' '*';
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
            add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain; charset=utf-8';
            add_header 'Content-Length' 0;
            return 204;
      }
         
      add_header 'Access-Control-Allow-Origin' '*';
      add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
      add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
         
      # 其他 Nginx 配置指令...
         
      # 代理到后端应用,例如使用 proxy_pass
      # proxy_pass http://your_backend_server;
    }

    # 其他 server 配置...
}

宝塔用户_qgqjfh 发表于 2024-4-17 19:14:56

运维技术南一 发表于 2024-4-17 17:46
您好,报错显示您的语法不正确,请您检查一下
这个是配置 Nginx 以允许来自任何源的跨域请求:,参考一下
s ...

首先,非常感谢你的指导,本人小白。
另外,请教我要设置仅允许我信任的网站访问,比如baidu.com,
又该如何设置呢,
还请指教一下,谢谢了。
我虚心学习。。。

阿珂 发表于 2024-5-7 17:54:15

可以参考下面配置:
    location / {
      deny all;
      allow 123.123.123.123; # 允许特定IP访问
      allow baidu.com; # 允许特定域名访问
      deny all;拒绝其他方式访问
    }
页: [1]
查看完整版本: 【已完成】允许Cors跨域访问,配置文件报错。