Apache + PHP Yii框架跨域访问API

其实不用在Yii框架中设置任何东西,直接用Ajax调用不同域名的API即可

但是Apache中要这么设置:

首先编辑httpd.conf    去掉这一句的注释:LoadModule headers_module modules/mod_headers.so

然后在httpd-vhosts.config文件种添加头信息

Header set Access-Control-Allow-Origin *    --意思是允许所有域名都可以访问
Header set Access-Control-Allow-Headers "access_token"  --如果有自定义的请求头,例如:access_token 则添加这一行

如果有自定义的请求头,不添加的话,则会报错:Request header field access_token is not allowed by Access-Control-Allow-Headers

如果用jsonp或者proxy的方式进行修改的话未免需要太大的工程量,所以采用CORS这种比较简单高效的技术。相比JOSP的方式,CORS更为高效。JSONP由于它的原理只能实现GET请求,而CORS支持所有类型的HTTP请求。使用CORS,可以使用普通的ajax实现跨域。

Header set Access-Control-Allow-Origin * 配置的含义是允许任何域发起的请求都可以获取当前服务器的数据。当然,这样有很大的危险性,恶意站点可能通过XSS攻击我们的服务器。所以我们应该尽量有针对性的对限制安全的来源,例如下面的设置使得只有http://123.com/这个域才能跨域访问服务器的API。Header set Access-Control-Allow-Origin http://123.com/


这是我的httpd-vhosts.config文件,设置了三个虚拟目录,具体参考:https://blog.csdn.net/baidu_41327283/article/details/82668757

# Virtual Hosts
#
<VirtualHost *:80>
ServerName mysite1.com
ServerAlias mysite1.com
DocumentRoot "${INSTALL_DIR}/www/ourchildren/jzymaosida-childrenfront-master/childrenfront/web"
<Directory "${INSTALL_DIR}/www/ourchildren/jzymaosida-childrenfront-master/childrenfront/web/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Headers "access_token"
</Directory>
</VirtualHost>


<VirtualHost *:80>
ServerName mysite2.com
ServerAlias mysite2.com
DocumentRoot "${INSTALL_DIR}/www/ourchildren/jzymaosida-our-children-web-develop/our-children-web/web"
<Directory "${INSTALL_DIR}/www/ourchildren/jzymaosida-our-children-web-develop/our-children-web/web/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Headers "access_token"
</Directory>
</VirtualHost>


<VirtualHost *:80>
ServerName mysite3.com
ServerAlias mysite3.com
DocumentRoot "${INSTALL_DIR}/www/ourchildren/jzymaosida-our-children-back-end-children-v1/our-children-back-end/backend/web"
<Directory "${INSTALL_DIR}/www/ourchildren/jzymaosida-our-children-back-end-children-v1/our-children-back-end/backend/web/">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Headers "access_token"
</Directory>
</VirtualHost>

原文地址:https://www.cnblogs.com/eric-qin/p/11434345.html