This article introduces to you how Nginx implements cross-domain access? The implementation of Nginx cross-domain access has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Cross-domain refers to requesting resources of another domain name from a web page of one domain name. For example, request the resources of www.b.com from the www.a.com page.
#Browsers generally prohibit cross-domain access by default. Because it is insecure, it is prone to CSRF (cross-site request forgery) attacks.
Nginx adds HTTP such as Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers, etc. header information to control browser caching.
"Access-Control-Allow-Origin" Set the website that is allowed to initiate cross-domain requests
"Access-Control-Allow-Methods" Set the HTTP methods that are allowed to initiate cross-domain requests
"Access -Control-Allow-Headers" setting allows cross-domain requests to include Content-Type headers
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
fileHello,I'm a!
nbsp;html> <meta> <title>Ajax跨站访问b</title> <h1>Ajax跨站访问b - </h1> <script></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>
nbsp;html> <meta> <title>Ajax跨站访问c</title> <h1>Ajax跨站访问c - </h1> <script></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>
C:\Windows\System32\drivers\etc\hostslinux:
/etc/hosts
192.168.33.88 www.a.com 192.168.33.88 www.b.com 192.168.33.88 www.c.com
and
http://www.c.com/index.html
# respectively.
Ajax跨站访问b - Hello,I'm a!
Ajax跨站访问c - 请求失败!
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.
Recommended related articles:
Nginx as a static resource web service to control browser cache and implement anti-leeching Nginx as a static resource web service and static resource compressionThe above is the detailed content of How does Nginx implement cross-domain access? Implementation of Nginx cross-domain access. For more information, please follow other related articles on the PHP Chinese website!