Apache + PHP Yii框架跨域访问API

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

可是Apache中要这么设置:ajax

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

而后在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/ide

 


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

# 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>ui


<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>

相关文章
相关标签/搜索