一、什么是跨域跨域是指从一个域名的网页去请求另一个域名的资源。比如从 www.a.com 页面去请求 www.b.com 的资源。
浏览器一般默认会禁止跨域访问。因为不安全,容易出现 csrf(跨站请求伪造)攻击。
二、nginx控制浏览器允许跨域访问nginx通过添加 access-control-allow-origin、access-control-allow-methods、access-control-allow-headers 等http头信息的方式控制浏览器缓存。
access-control-allow-origin 设置允许发起跨域请求的网站
access-control-allow-methods 设置允许发起跨域请求请求的http方法
access-control-allow-headers 设置允许跨域请求包含 content-type头
ngx_http_headers_module语法syntax: add_header name value [always];default: —context: http, server, location, if in location
应用实例1. vim conf.d/cross_site.conf# 配置网站www.a.comserver { 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.comserver { server_name www.b.com; root /vagrant/b;}# 配置网站www.c.comserver { server_name www.c.com; root /vagrant/c;}
2. nginx -s reload 重新载入nginx配置文件3. 创建 /vagrant/a/a.txt、/vagrant/b/index.html、/vagrant/c/index.html 文件vim /vagrant/a/a.txt
hello,i'm a!
/vagrant/b/index.html
<!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>
/vagrant/c/index.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>
4. 配置客户端的hosts文件(使用真是域名的可以忽略)windows: c:\windows\system32\drivers\etc\hosts
linux: /etc/hosts
添加如下内容,并保存(192.168.33.88为笔者虚拟机的ip,需自行替换为自己的ip):
192.168.33.88 www.a.com192.168.33.88 www.b.com192.168.33.88 www.c.com
5. 浏览器分别访问 http://www.b.com/index.html 和 http://www.c.com/index.htmlhttp://www.b.com/index.html
ajax跨站访问b - hello,i'm a!
http://www.c.com/index.html
ajax跨站访问c - 请求失败!
打开浏览器的开发者模式console,还可以发现 http://www.c.com/index.html 的页面出现报错:
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.
相关文章推荐:
nginx作为静态资源web服务来控制浏览器缓存以及实现防盗链
nginx作为静态资源web服务并进行静态资源压缩
以上就是nginx如何实现跨域访问?nginx跨域访问的实现的详细内容。
