Nginx 配置解决跨域问题

目录

一、前言

二、解决方案

1、方案一

2、方案二


一、前言

现在大部分的项目都是前后端分离的项目,这种项目前端访问后端一般都是会使用域名来访问,请求接口时,浏览器会报错:Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. 当遇到这种跨域的问题时,本文介绍一种使用Nginx来解决的办法。

二、解决方案

1、方案一

使用以下配置解决,在nginx配置文件中增加以下配置。

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

例如:

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、方案二

但是有的时候,加了这种配置还是会出现跨域的问题,这个时候我们可以再尝试以下方法,指定具体的域名。

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

配置改动后如下:

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

注意:

1. Access-Control-Allow-Origin
服务器默认是不允许跨域的,给Nginx服务器配置 Access-Control-Allow-Origin *; 后的含义,表示服务器可以接受所有的请求源,即接受所有跨域的请求。但是这样设置在项目中并没有解决跨域,但是设置了具体的项目域名,比如 http://a.xxx.com 后,就可以跨域了;这有些不符合常理,但是情况确实如此;

猜你喜欢

转载自blog.csdn.net/Wjhsmart/article/details/115738570