Nginx cross-domain implementation

First of all, you need to understand what cross-domain is and why cross-domain occurs. Which cases are cross-domain?

Cross-domain: Pages belonging to different domains cannot access each other due to the same origin policy of the browser

Note: The same origin policy simply means same protocol, same domain name, same port

URL indicates whether communication is allowed

www.a.com/a.js www.a.com/b.js allowed under the same domain name www.a.com/lab/a.js www.a.com/script/b.js allowed for different folders under the same domain name www.a.com/b.js :8000/ A.js www.a.com/b.js Same domain name, different ports are not allowed www.a.com/a.js www.a.com/b.js Same domain name, Different protocols www.a.com/a.js http://70.32.92.74/b.js domain name and corresponding IP address www.a.com/a.js script.a.com/b.js The primary domain is the same. Different subdomains are not allowed www.a.com/a.js a.com/b.js The same domain name, different secondary domain names (same as above) are not allowed (cookie is not allowed) www.cnblogs.com/a.js www.a.com/b.js Different domain names are not allowed

Cross-domain scenario

For security reasons (such as CSRF attacks), browsers generally forbid cross-domain access, but sometimes there is a need to allow cross-domain access, so cross-domain access restrictions need to be turned on. Start a Web service on port 8081Then start a Web service/front-end service. The port is 8082, and then the 8082 service is accessed through Ajax, which does not meet the same origin policy and causes 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 call" onclick="fun1()">
</html>
Copy the code

Solutions to cross-domain problems

There are also multiple ways to solve cross-domain problems.

1. Combination of front and back ends (JsonP)

Although JSONP can be cross-domain, it is not covered here because jSONP does not support POST requests and is very limited in application scenarios.

2. Pure back-end mode 1 (CORS mode)

CORS is a W3C standard way of setting up on the Web server: The access-cntro-alow-origin header specifies which domain can Access the data in the local domain. Internet explorer 8&9(XDomainRequest), 10+, chrome m4, firefox3.5,safair4, opera12 support this method.

Server proxy: The same origin policy exists only on the browser side. Forwarding requests through the server can achieve the purpose of cross-domain requests. Disadvantages: Increasing the server burden and slow access speed.

3. Pure backend mode 2 (Nginx proxy mode)

Configure the Nginx reverse proxy first

Proxy access normal

8082 service access to Nginx, cross-domain problems occurred

Nginx configuration 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;
} 
Copy the code

Cross domain problems are solved

Parameters that

Access-Control-Allow-Origin

Servers are not allowed to cross domains by default. Access-control-allow-origin * indicates that the Nginx server can accept all Origin requests.

Access-Control-Allow-Headers

Is to prevent the following errors:

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

This error indicates that the value of the current request content-Type is not supported. The result is that we made a request of type “application/json”. There is a concept involved here: preflight requests. See “Preflight requests” below.

Access-Control-Allow-Methods

Is to prevent the following errors:

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

Add 204 return to OPTIONS

To handle the error that Nginx still denies access when sending a POST request, the server needs to allow the method OPTIONS when sending a “precheck request”.

Preflight Request

The Cross-domain Resource Sharing (CORS) standard adds a new set of HTTP header fields that allow servers to declare which source sites have access to which resources. In addition, the specification requires that HTTP request methods (especially HTTP requests other than GET, or POST requests paired with certain MIME types) that may have adverse effects on server data, The browser must first issue a preflight request using the OPTIONS method to know whether the server will allow the cross-domain request. The actual HTTP request is made only after the server confirms that it is allowed. In the return of the precheck request, the server side can also inform the client whether it needs to carry identity credentials (including Cookies and HTTP authentication related data). A POST request with a content-type of application/json is a POST request with a MIME Type. CORS specifies that a content-type is not a POST request with a MIME Type of application/json. The application/ JSON Request will add a “pre-check” Request before formal communication. This “pre-check” Request will carry the access-Control-request-headers: content-type: