問題原因: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/