Nginx · 8月 29, 2021 0

Nginx解决跨域资源问题:No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

想给HENCH@T主域名https://henchat.ml的Nginx加个反向代理到https://blog.henchat.ml。结果加好后发现网页能刷出来,但字体加载不了。按F12发现大量报错:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

解决办法

反代对象看来不支持跨域访问呀。那我们就让它支持。要修改blog.henchat.ml的nginx.conf设置。只需在location部分插入以下代码👇

location / {
    add_header 'Access-Control-Allow-Origin' http_origin;
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,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') {
        add_header 'Access-Control-Max-Age' 1728000;
        add_header 'Content-Type' 'text/plain; charset=utf-8';
        add_header 'Content-Length' 0;
        return 204;
    }
    # 其他内容
}

重启Nginx服务。这回应该能解决了。