nginx Access-Control-Allow-Origin css跨域

问题原因:nginx 服务器 css 字体跨域 以及img相对路径 问题

 

描述:用nginx做页面静态化时遇到了两个问题

1.我有两个静态资源服务器 static.xxx.com  和 item.xxx.com 。我的字体文件存在 static.xxx.com上,在用item.xxx.com 访问 static.xxx.com 的时候浏览器报以下错误

 Font from origin 'http://static.xxx.com' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Origin 'http://item.xxx.com' is therefore not allowed access.

问题的本质就是 css跨域请求。

 

Nginx 解决办法:

add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;

将这段代码添加到 http{} 或者静态资源对应的 server{} 中, 

如果只为自己的网站使用可以将第一行代码的星号改为自己的域名,例如 *.xxx.org

 

2.图片的相对路径  <img src="/pictrue/1.jpg"/>

 img 的相对路径是从 网站的根目录下开始查找,为了简单我把图片放到静态页面的跟目录下

 

参考链接:https://blog.fbzl.org/access-control-allow-origin-%E8%A7%A3%E5%86%B3%E8%B7%A8%E5%9F%9F%E6%9D%83%E9%99%90%E9%97%AE%E9%A2%98/

 

posted @ 2017-01-10 16:05  未来--  阅读(6526)  评论(0编辑  收藏  举报