IT 相关 · 2024 年 8 月 19 日

Nginx 配置请求头以解决 CORS 跨域问题

当站点未包含 Access-Control-Allow-Origin 请求头时,根据 CORS 将不被允许访问,这个问题出现在独立静态资源站被其它域的网站引用时发生,尤其是发生在前后端部署的站点,在打开 Chrome 开发者工具进行调试时出现错误:from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

配置以下 Nginx 代码以解决。

    # 允许所有来源访问
    add_header 'Access-Control-Allow-Origin' '*';

    # 允许的请求方法
    add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';

    # 允许的请求头
    add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

    # 允许预检请求缓存时间
    add_header 'Access-Control-Max-Age' '1728000'; # 20 天

    # 预检请求
    if ($request_method = 'OPTIONS') {
        add_header 'Access-Control-Allow-Origin' '*';
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, DELETE, PUT';
        add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
    }