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 Under the same domain name allow Different folders under the same domain name allow The same domain name , Different ports Don't allow The same domain name , Different protocols Don't allow Domain names correspond to domain names ip Don't allow Primary domain is the same , Different subdomains Don't allow The same domain name , Different secondary domains ( ditto ) Don't allow (cookie Access is also not allowed in this case ) 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

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

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 .

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

   First configuration Nginx The reverse proxy mode of

Proxy access is normal

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

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;

Solved cross domain problems

Parameter description


   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 .


   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 .


   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:

An article lets you understand how to pass Nginx To solve cross domain problems

  1. Learn in five minutes Java: An article will take you to understand spring The whole family meal

    Original statement This article was first published on WeChat public [ Programmer Huang Xiaoxie ] The author of this article : Huang Xiaoxie For reprint, please indicate the source and the author at the beginning of the article . This article's mind map What is? Spring, Why do you want to learn spring? Your first contact with spring The frame is in the ...

  2. An article will take you to understand SpringBoot And Swagger Integrate

    Swagger Use because I don't like csdn Of markwoen Editor , Poor support for code styles , I don't feel comfortable , Students with higher aesthetic requirements move forward github: ...

  3. An article to make you understand SSL certificate

    About marriage That day, I discussed with my colleagues what is real 「 marry 」? This kind of topic should never exist . A certificate in the traditional sense , Have a wedding . Eat, drink , But with the physical and mental development and evolution of people of all ethnic groups in society , The original cumbersome process is anti human , It seems that ...

  4. An article will take you to understand etcd 3.5 The core feature of

    author Tang Cong , Senior engineer of Tencent cloud , Geek hour <etcd Practical course > author ,etcd Active contributors , Mainly responsible for Tencent cloud k8s/etcd platform . Stateful service containerization . In the off-line mixing department and other product development and design work . etcd ...

  5. An article for you to understand Pivotal Of GemFire Family products

    An article for you to understand Pivotal Of GemFire Family products To study the :

  6. An article will take you through ElasticSearch The term

    This article mainly introduces ElasticSearch Basic concepts of , Learning documents . Indexes . colony . node . Concepts such as segmentation , At the same time ElasticSearch Make a simple analogy with a relational database , It will also briefly introduce REST API The emissary of ...

  7. An article teaches you to understand Makefile

    makefile Very important       What is? makefile? Maybe a lot Winodws None of our programmers know about it , Because of those Windows Of IDE They've done this job for you , But I feel like making a good one and professiona ...

  8. An article for you to understand OpenStack The origin of 、 Architecture and application

    OpenStack It's a face IaaS Layer of open source projects , It is used to realize the deployment and management of public cloud and private cloud . It has industry endorsements from many large companies and thousands of community members , OpenStack Seen as the future of Cloud Computing . at present OS The foundation ...

  9. An article takes you to understand AWS re:Invent 2018 The conference , reveal Amazon Aurora

    This article is You Yun. + Community publication | The author of this article : Liu Feng , Tencent cloud NewSQL Database product owner . He worked in Lenovo Research Institute ,Teradata Beijing R & D Center , Engaged in database related work 8 year .2017 Joined Tencent database product center in , As a NewSQL ...

  10. An article teaches you to understand UI Drawing process

    Recently, many people have asked me Android I don't have the confidence to further study , Can't find a good job , In fact, I reply with one of them , I found that they were mainly impetuous , You know, the technology industry is always short of experts . It's suggested to read the book first Android Trend analysis , At work , ...

Random recommendation

  1. Linux Learning notes (16)- Multithreading

    What is multithreading ? Or say , What is thread ? According to the description in the book , Threads , It is the sequential execution flow contained in the process , It's the unit that actually works in the process , It is also the smallest unit that the operating system can schedule . Multiple threads can be concurrent in a process , Each thread executes in parallel ...

  2. UpdatePane Pop up box in

    ScriptManager.RegisterClientScriptBlock(this.UpdatePanel21, typeof(UpdatePanel), " Tips ",&quo ...

  3. Script learning python and linux-shell and jQuery(javascript)

    Using scripts makes it easy to manage , Using computers . I'm going to learn how to use the computer system better , especially Linux. learn python Because it's open source , And it's C The language of the family , Originally, the course needs , Plus it's really good , So it's very important , I've seen it before perl ...

  4. vim Key mapping in

    The composition of key mapping keywords began to confuse me , Checked the data , And then make a log Key binding command : Pattern prefix ( Default is normal) + Recursive prefix ( The default is empty ) + map The prefix indicates the effective range , Recursive prefixes indicate whether to recursively look up commands ...

  5. Jquery Text scroll up and down effect example code

      <!doctype html>   <html>   <head>   <meta charset="utf-8">       ...

  6. Flume-ng Source code analysis Source Components

    If you haven't seen Flume-ng The startup process in the source code analysis series .Channel Components and Sink Components , You can click on the link below : Flume-ng Source code analysis of the start process Flume-ng Source code analysis Channel Components Flum ...

  7. split add to limit Parameters

    String str = "I love you"; /** It is divided into I and love you**/ String[] spiltStr = str.spit(" &qu ...

  8. 《mysql Will know 》 Study _sql File import database _20180724_ huan

    solve the problem 1:MySQL Import sql file . step 1:show databases;# Look what database I have step 2:use hh;# I want to use hh This database , return database changed It indicates that it was opened successfully . ...

  9. java The reference of the parent class calls its own property But the method to be called must be the method of the overridden parent class Because the compiler takes it as a parent class It's him when he runs So you must override the method of the parent class

  10. Swift Learning notes - Swift Properties are read-only

    stay OC We often use read-only properties in , use readonly Just decorate it , But in Swift This is no longer the case in , Let's record Swift Use of read-only properties in stay OC Read only in : // Read-only property @property(rea ...