目录
问题描述:
front.local.com 为前端网站(A站), img.local.com 为图片站(B站),当A站中的js访问到B站资源时,报错误:"The image has been blocked by CORS policy",即浏览器的同源策略限制了访问。
服务器端解决方案
- Apache2
首先, 确定apahe2.conf 有mod_headers支持
LoadModule headers_module /usr/lib/apache2/modules/mod_headers.so
其次,
方法一:单独在图片站(B站)虚拟主机配置加 Headers
<VirtualHost *>
ServerAdmin admin@php5
ServerName img.local.com
ServerAlias *.img.local.com
DocumentRoot "{path}"
Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header set Access-Control-Allow-Credentials true
Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization"
<Directory "{path}">
# use mod_rewrite for pretty URL support
RewriteEngine on
# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
RewriteRule . index.php
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
方法二:全局起效,修改apache2.conf
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin: "*"
Header set Access-Control-Allow-Methods: "GET,POST,PUT,DELETE,OPTIONS"
Header set Access-Control-Allow-Headers: "Content-Type"
</IfModule>
- Nginx
server {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
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';
if ($request_method = 'OPTIONS') {
return 204;
}
}