current position:Home>An article lets you understand how to solve cross domain problems through nginx

An article lets you understand how to solve cross domain problems through nginx

2021-08-25 17:40:04 dengpengbo

Nginx Cross domain implementation

   First of all, we should make clear what is cross domain , Why do cross domain situations occur . Which cases are cross domain ?

Cross domain : Because of the browser's same origin policy , That is, the pages belonging to different fields cannot visit each other's page content
notes : The same-origin policy , It's just an agreement , Same as domain name , Same port

URL explain Whether to allow communication
http://www.a.com/a.js
http://www.a.com/b.js Under the same domain name allow
http://www.a.com/lab/a.js
http://www.a.com/script/b.js Different folders under the same domain name allow
http://www.a.com:8000/a.js
http://www.a.com/b.js The same domain name , Different ports Don't allow
http://www.a.com/a.js
https://www.a.com/b.js The same domain name , Different protocols Don't allow
http://www.a.com/a.js
http://70.32.92.74/b.js Domain names correspond to domain names ip Don't allow
http://www.a.com/a.js
http://script.a.com/b.js Primary domain is the same , Different subdomains Don't allow
http://www.a.com/a.js
http://a.com/b.js The same domain name , Different secondary domains ( ditto ) Don't allow (cookie Access is also not allowed in this case )
http://www.cnblogs.com/a.js
http://www.a.com/b.js Different domain name Don't allow

Cross domain scenario

   For safety reasons ( such as csrf attack ), Browsers generally prohibit cross domain access , But because sometimes there's a need , Need to allow cross domain access to , At this time , We need to turn on cross domain access restrictions .
   Start a web service , The port is 8081
 Insert picture description here
   Then turn on one more web service / Front end services are OK . The port is 8082, And then again 8082 Service through ajax To visit 8081 Service for , This does not satisfy the homology strategy , There will be cross domain problems

<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
</head>
<body>
<h2>Hello World!</h2>
<script type="text/javascript">
    function fun1(){
        var request = new XMLHttpRequest();
        request.open("GET","http://localhost:8081/user/query")
        request.send();
        request.onreadystatechange = function(){
            if(request.status==200 && request.readyState == 4){
                console.log(" The result of the response " + request.responseText)
            }
        }
    }
</script>
</body>
    <input type="button" value=" Cross-domain calls " onclick="fun1()">
</html>

 Insert picture description here

Solutions to cross domain problems

   There are many ways to solve cross domain problems .

1、 Combination of anterior and posterior ends (JsonP)

   although jsonp You can also implement cross-domain , But because jsonp I won't support it post request , Application scenarios are very limited , So it's not right here jsonp Introduction .

2、 Pure back end mode one (CORS The way )

  CORS yes w3c Standard way , By means of web Server settings : Response head Access-Cntrol-Alow-Origin To specify which domains can access the data of this domain ,ie8&9(XDomainRequest),10+,chrom4,firefox3.5,safair4,opera12 Support this way .

   Server agent , The same origin policy only exists on the browser side , Forwarding the request through the server can achieve the purpose of cross domain request , Inferiority : Increase server burden , And slow access .

 Insert picture description here

3. Pure back end mode 2 (Nginx Agency mode )【 Suggest this way 】

   First configuration Nginx The reverse proxy mode of
 Insert picture description here

Proxy access is normal
 Insert picture description here

8082 Service access for Nginx, There's a cross domain problem

 Insert picture description here

Nginx Configure cross domain resolution

location / {  
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods 'GET, POST, OPTIONS';
    add_header Access-Control-Allow-Headers 'DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization';

    if ($request_method = 'OPTIONS') {
        return 204;
}
proxy_pass http://192.168.12.1:8081;
} 

Solved cross domain problems
 Insert picture description here

Parameter description

Access-Control-Allow-Origin

   Servers are not allowed to cross domain by default . to Nginx Server configuration Access-Control-Allow-Origin * after , Indicates that the server can accept all request sources (Origin), That is to accept all cross domain requests .

Access-Control-Allow-Headers

   Is to prevent the following mistakes :

Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

   This error indicates the current request Content-Type The value of is not supported . In fact, we initiated "application/json" The type request of . Here's a concept : Pre inspection request (preflight request), Please see the following " Pre inspection request " Introduction to .

Access-Control-Allow-Methods

   Is to prevent the following mistakes :

Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

to OPTIONS add to 204 Return

   It's to deal with sending POST When asked Nginx Still deny access error , send out " Pre inspection request " when , You need to use methods OPTIONS , So the server needs to allow this method .

Pre inspection request (preflight request)

   Cross-domain resource sharing (CORS) There's a new set of standards HTTP Header field , Allow the server to declare which origin has access to which resources . in addition , Specification requirements , For those that may have side effects on server data HTTP Request method ( especially GET Outside of the HTTP request , Or something MIME Type of POST request ), Browsers must first use OPTIONS Method to initiate a pre check request (preflight request), So we can know whether the server allows the cross domain request . After the server confirms the permission , To launch the actual HTTP request . In the return of the pre check request , The server can also notify the client , Do you need to carry ID card ( Include Cookies and HTTP Certification related data ).
   Actually Content-Type The type of field is application/json The request is to match some of the above MIME Type of POST request ,CORS Regulations ,Content-Type It doesn't belong to the following MIME Type of , It's all pre inspection requests
   therefore application/json Request Will be before formal correspondence , Add a " preview " request , This time, " preview " The request comes with a header Access-Control-Request-Headers: Content-Type:

copyright notice
author[dengpengbo],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210825174002754i.html

Random recommended