Nginx 實現AJAX跨域請求

來源:互聯網
上載者:User
更多:http://www.webyang.net/Html/web/article_135.html

最新的W3C標準裡是這麼實現HTTP跨域請求的,

Cross-Origin Resource Sharing
簡單來說,就是跨域的目標伺服器要返回一系列的Headers,通過這些Headers來控制是否同意跨域。
這些Headers有:
4 Syntax
4.1 Access-Control-Allow-Origin HTTP Response Header
4.2 Access-Control-Max-Age HTTP Response Header
4.3 Access-Control-Allow-Credentials HTTP Response Header
4.4 Access-Control-Allow-Methods HTTP Response Header
4.5 Access-Control-Allow-Headers HTTP Response Header
4.6 Origin HTTP Request Header
4.7 Access-Control-Request-Method HTTP Request Header
4.8 Access-Control-Request-Headers HTTP Request Header
在 Request 包和 Response 包中都有一些。
其中最敏感的就是 Access-Control-Allow-Origin 這個 Header, 他是W3C標準裡用來檢查該跨域請求是否可以被通過。 (Access Control Check)
所以如果需要跨域,解決方案就是在資源的頭中加入 Access-Control-Allow-Origin 指定你授權的域. 我這裡無所謂,就指定星號 * , 任何域都可以訪問我的資源。

具體操作方法, 可以通過不同入口來控制:

一、php代碼控制:
 
  1. php
  2. header("Access-Control-Allow-Origin: *");
  3. ?>
二、html頭控制:
 
  1. http-equiv="Access-Control-Allow-Origin"content="*">
三、nginx配置:
 
  1. location /{
  2. add_header Access-Control-Allow-Origin*;
  3. }
在網上看到有人會在nginx.conf加三句話:
 
  1. #授權從other.subdomain.com的請求
  2. add_header 'Access-Control-Allow-Origin''http://other.subdomain.com';
  3. #當該標誌為真時,響應於該請求是否可以被暴露
  4. add_header 'Access-Control-Allow-Credentials''true';
  5. #指定請求的方法,可以是GET,POST等
  6. add_header 'Access-Control-Allow-Methods''GET';

不過我自己測試了一下,是不需要的。另如果要指定特定的網域名稱,只要修改*即可,一般都是開放網站的次層網域。

以上就介紹了Nginx 實現AJAX跨域請求,包括了方面的內容,希望對PHP教程有興趣的朋友有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.