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>

相關文章
相關標籤/搜索