跨域是指從一個域名的網頁去請求另外一個域名的資源。好比從 www.a.com 頁面去請求 www.b.com 的資源。html
瀏覽器通常默認會禁止跨域訪問。由於不安全,容易出現 CSRF(跨站請求僞造)攻擊。jquery
Nginx經過添加 Access-Control-Allow-Origin、Access-Control-Allow-Methods、Access-Control-Allow-Headers 等HTTP頭信息的方式控制瀏覽器緩存。linux
"Access-Control-Allow-Origin" 設置容許發起跨域請求的網站
"Access-Control-Allow-Methods" 設置容許發起跨域請求請求的HTTP方法
"Access-Control-Allow-Headers" 設置容許跨域請求包含 Content-Type頭
Syntax: add_header name value [always]; Default: — Context: http, server, location, if in location
# 配置網站www.a.com server { server_name www.a.com; root /vagrant/a; # 容許 http://www.b.com 使用 GET,POST,DELETE HTTP方法發起跨域請求 add_header Access-Control-Allow-Origin http://www.b.com; add_header Access-Control-Allow-Method GET,POST,DELETE; } # 配置網站www.b.com server { server_name www.b.com; root /vagrant/b; } # 配置網站www.c.com server { server_name www.c.com; root /vagrant/c; }
/vagrant/a/a.txt
、/vagrant/b/index.html
、/vagrant/c/index.html
文件Hello,I'm a!
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Ajax跨站訪問b</title> </head> <body> <h1>Ajax跨站訪問b - </h1> </body> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script> $(function(){ $.ajax({ url: "http://www.a.com/a.txt", type: "GET", success: function (data) { $('h1').append(data); }, error: function (data) { $('h1').append('請求失敗!'); } }); }) </script> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Ajax跨站訪問c</title> </head> <body> <h1>Ajax跨站訪問c - </h1> </body> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script> $(function(){ $.ajax({ url: "http://www.a.com/a.txt", type: "GET", success: function (data) { $('h1').append(data); }, error: function (data) { $('h1').append('請求失敗!'); } }); }) </script> </html>
windows: C:\Windows\System32\drivers\etc\hosts
linux: /etc/hosts
nginx
添加以下內容,並保存(192.168.33.88爲筆者虛擬機的IP,需自行替換爲本身的IP):ajax
192.168.33.88 www.a.com 192.168.33.88 www.b.com 192.168.33.88 www.c.com
http://www.b.com/index.html
和 http://www.c.com/index.html
Ajax跨站訪問b - Hello,I'm a!
Ajax跨站訪問c - 請求失敗!
打開瀏覽器的開發者模式Console,還能夠發現 http://www.c.com/index.html 的頁面出現報錯:vim
Failed to load http://www.a.com/a.txt: The 'Access-Control-Allow-Origin' header has a value 'http://www.b.com' that is not equal to the supplied origin. Origin 'http://www.c.com' is therefore not allowed access.