Nginx/同源策略

来自康健生活
Kangkk​(留言 | 贡献)2025年4月14日 (一) 07:45的版本 (创建页面,内容为“== 标题文本 == == Access-Control-Allow-Origin == <pre> server { listen 80; server_name example.com; location / { # 允许所有域名跨域 add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; # Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response. add_header 'Access-Control-Allow-Headers' 'DNT,X-Mx…”)
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

标题文本

Access-Control-Allow-Origin

server {
    listen 80;
    server_name example.com;

    location / {
        # 允许所有域名跨域
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
        # Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
        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,Range';
        # 允许客户端访问的响应头
        # Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
        add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';

        # 处理 OPTIONS 预检请求
        if ($request_method = 'OPTIONS') {
            add_header 'Access-Control-Max-Age' 1728000;
            add_header 'Content-Type' 'text/plain; charset=utf-8';
            add_header 'Content-Length' 0;
            return 204;
        }

        # 其他配置
        # proxy_pass http://backend;
    }
}

多域名

# 定义允许的域名
map $http_origin $cors_origin {
    default "";
        "~^https://example.com$" $http_origin;
        "~^https://another.com$" $http_origin;
}

server {
    listen 80;
    server_name example.com;

    location / {
        # 动态设置允许的域名
        add_header 'Access-Control-Allow-Origin' $cors_origin;
        # 其他配置
    }
}