Nginx forward proxy solves cross-domain problems

principle

In order to better understand the principle of nginx to solve cross-domain, let's first understand how cross-domain is generated.
Because of the browser's same-origin policy, cross-domain will occur. For example, the asynchronous requests sent are from two different sources, such as two different ports or two different protocols or different domain names. For security reasons, the browser will generate a same-origin policy, and those that are not from the same place are not allowed to interact. The same-origin policy only exists in the browser, that is, the browser needs to follow the same-origin policy when it communicates with the server, and it does not need to be followed between servers. Nginx acts as a proxy server between the browser and the server, enabling data transmission from the same source as the browser.

configuration

1. First analyze the request interface

 axios.get('http://www.aaa.com:8081/api/blog/getList').then(res=>{
    
    
          console.log(res)
        })

The server interface address requested here is http://localhost:8081/api/blog/getList, and then nginx can be configured

2. Change the request to the same source address as the website

Assuming that the website address currently sending the request is http://www.aaa.com (default port 80), modify the request address to an address of the same origin as the website.

 axios.get('http://www.aaa.com/api/blog/getList').then(res=>{
    
    
          console.log(res)
        })

3. Find the nginx.conf file in the /…/nginx/conf directory, enter the file for configuration

http      
{
    
    
	...
	server
	{
    
    
	    #表示监听发送请求的地址(www.aaa.com:80)
        listen       80; 
        server_name  www.aaa.com;
        #如果监听到请求接口地址是 www.aaa.com/api/blog/getList ,nginx就向http://www.aaa.com:8081/api/blog/getList 这个地址发送请求
        location /api/ {
    
     #判过滤出含有api的请求
            proxy_pass http://www.aaa.com:8081; #真实服务器的地址
        }
 	}
}

The simplest configuration is implemented here. If you need more specific configuration properties, please visit: nginx configuration details

4. Test the configuration file (nginx.conf), then restart nginx

4.1. Test configuration file:

nginx -t

4.2. Execute the following statement to restart nginx

nginx -s reload

or

#停止nginx
nginx -s stop
#启动nginx
nginx

After completing the above operation and then sending the request, the data can be successfully obtained, which realizes the forward proxy of nginx to solve the cross-domain problem.

Guess you like

Origin blog.csdn.net/jiangjunyuan168/article/details/124293287