Use Nginx to solve cross-domain problems

Use Nginx to solve cross-domain problems

nginx version: (check nginx command: /usr/local/nginx/sbin/nginx -v)
nginx/1.4.3

The problem is: the front-end project domain name is a.xxxx.com, the back-end interface domain name is b.xxx.com, and then the back-end interface does not set cross-domain related response headers, so there
will be cross-domain connections between the interface and our domain name situation, so we can use the nginx server to configure it;

A lot of information on the Internet will add the following code under the nginx configuration to solve the cross-domain problem;

add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods GET,POST;

For example, the following configuration on nginx:

server {
    listen 443;
    listen 80;
    server_name b.xxx.com;
    access_log  /data/www/logs/nginx/access.log main;

    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Credentials true;
    add_header Access-Control-Allow-Methods GET,POST;

    include nginx_xxx.conf;
    location / {
        proxy_pass http://192.168.1.212:8136;
        #proxy_pass http://xd-mfa-mng/;
        include nginx_proxy.conf;
    }
    error_page   500 502 503 504  /502.html;
    location = /50x.html {
        oot   html;
    }
}

But there will still be cross-domain situations. As the saying goes, dreams are beautiful, but reality is cruel. Therefore, we need to specify the corresponding domain name to solve the above cross-domain problem .

add_header Access-Control-Allow-Origin http://a.xxx.com; 

With the above configuration, you can use nginx to solve the cross-domain problem;

So the code becomes as follows:

server {
    listen 443;
    listen 80;
    server_name b.xxx.com;
    access_log  /data/www/logs/nginx/access.log main;

    add_header Access-Control-Allow-Origin http://a.xxx.com; 
    add_header Access-Control-Allow-Credentials true;

    include nginx_xxx.conf;
    location / {
        proxy_pass http://192.168.1.212:8136;
        #proxy_pass http://xd-mfa-mng/;
        include nginx_proxy.conf;
    }
    error_page   500 502 503 504  /502.html;
    location = /50x.html {
        oot   html;
    }
}

Notice:

1. The Access-Control-Allow-Origin
server does not allow cross-domain by default. Configure the Nginx server with the meaning after Access-Control-Allow-Origin *;, which means that the server can accept all request sources, that is, accept all cross-domain requests. ask. However, this setting does not solve cross-domain in the project, but after setting a specific project domain name, such as http://a.xxx.com, you can cross-domain; this is somewhat unreasonable, but it is the case;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324805617&siteId=291194637