Nginx configuration solves cross-domain problems

Table of contents

I. Introduction

Two, the solution

1. Option 1

2. Scheme 2


I. Introduction

Most of the projects now are separated from the front-end and the back-end. The front-end access to the back-end of this kind of project is generally accessed using a domain name. When requesting an interface, the browser will report an error: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.  When encountering such cross-domain problems, this article introduces a solution using Nginx.

Two, the solution

1. Option 1

Use the following configuration to solve, add the following configuration to the nginx configuration file.

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

For example:

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;
    }
}

2. Scheme 2

But sometimes, there will still be cross-domain problems after adding this configuration. At this time, we can try the following method to specify a specific domain name.

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

After the configuration changes are 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, and the meaning after configuring Access-Control-Allow-Origin *; for the Nginx server 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, it can cross-domain; this is somewhat unreasonable, but it is true;

Guess you like

Origin blog.csdn.net/Wjhsmart/article/details/115738570