This article introduces you to how Nginx can achieve cross-domain access? Nginx cross-domain access to the implementation, there is a certain reference value, the need for friends can refer to, I hope to help you.
One, what is cross-domain
Cross-domain refers to a resource that requests another domain name from a Web page of a domain name. For example, from the Www.a.com page to request www.b.com resources.
Browsers generally prohibit cross-domain access by default. Because it is unsafe, CSRF (cross-site request forgery) attacks are prone to occur.
Second, Nginx Control browser allows cross-domain access
Nginx by adding Access-control-allow-origin, Access-control-allow-methods, access-control-allow-headers such as HTTP header information to control the browser cache.
"Access-control-allow-origin" setting allows Web sites to initiate cross-domain requests
The "access-control-allow-methods" setting allows HTTP methods to initiate cross-domain request requests
"Access-control-allow-headers" setting allows cross-domain requests to include Content-type headers
Ngx_http_headers_module
Grammar
Syntax: add_header Name value [always];D efault: -context: http, server, location, if in location
Application examples
1. Vim conf.d/cross_site.conf
# Configure Web site www.a.comserver { server_name www.a.com; root/vagrant/a; # Allow http://www.b.com to initiate cross-domain requests Add_header access-control-allow-origin http://www.b.com using Get,post,delete http method ; Add_header Access-control-allow-method Get,post,delete;} # Configure Web site www.b.comserver { server_name www.b.com; root/vagrant/b;} # Configure Web site www.c.comserver { server_name www.c.com; ROOT/VAGRANT/C;}
2. Nginx-s Reload re-loading the Nginx configuration file
3. Create /vagrant/a/a.txt
, /vagrant/b/index.html
/vagrant/c/index.html
file
Hello,i ' m A!
<! DOCTYPE html>
<! DOCTYPE html>
4. Configure the client's Hosts file (with the real domain name can be ignored)
Windows:C:\Windows\System32\drivers\etc\hosts
Linux:/etc/hosts
Add the following, and save (192.168.33.88 as the author of the virtual machine's IP, the need to replace their own IP):
192.168.33.88 www.a.com192.168.33.88 www.b.com192.168.33.88 www.c.com
5. The browser accesses http://www.b.com/index.html
andhttp://www.c.com/index.html
Ajax cross-site access B-hello,i ' m A!
Ajax Cross-site access C-Request failed!
Open the browser's developer mode console, you can also find http://www.c.com/index.html page error:
Failed to load http://www.a.com/a.txt:The ' Access-control-allow-origin ' header had a value ' http://www.b.com ' that's not Equal to the supplied origin. Origin ' http://www.c.com ' is therefore not allowed access.