Skip to content
本页目录

Nginx 解决跨域问题

Nginx跨域解决配置示例

  • 跨域是浏览器的安全策略造成的,但其也是必要的,不能为了方便而放弃安全性
  • 跨域是不同源的请求导致的:IP、域名、端口等不同都会造成跨域
  • 跨域的判断是由请求头和响应头的相关字段进行判断的,这个是设置的基础

那解决方法目前看来有三个:

  • 前端层面自己解决:前端请求时自己进行代理
  • 网关层面进行解决:在nginx、kong同统一网关中进行配置解决
  • 服务后台解决:在Go、Java Web中进行配置解决,经典的Cors配置

有时候是只能使用一样跨域解决方式的,最终的效果是需要保证最后前端收到的请求头符合规范,特别是下面这个头:

Access-Control-Allow-Origin: *

如果返回的响应头里面少了会跨域,但多了,比如返回了两个相同的,也会跨域

注:在实际开发中,如果发生跨域,排查的第一步就是看看响应头里面是否返回了正确的数据,这样就能精确的进行下一步的解决操作

Nginx配置

下面展示如果通过配置Nginx解决跨域问题:

配置两个服务,监听在相同的端口,服务名不同而已,在转发配置中加上跨域配置,示例文件如下:

vim
# For more information on configuration, see:
#   * Official English Documentation: http://nginx.org/en/docs/
#   * Official Russian Documentation: http://nginx.org/ru/docs/

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;

# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;

events {
    worker_connections 1024;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

    # 转发websocket需要的设置
    proxy_set_header X-Real_IP $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X_Forward_For $proxy_add_x_forwarded_for;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';

    # Service1服务配置
    server {
        listen       80;
        server_name  www.service1.com;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
            proxy_pass http://localhost:8188/;
            # 设置是否允许 cookie 传输
            add_header Access-Control-Allow-Credentials true;
            # 允许请求地址跨域 * 做为通配符
            add_header Access-Control-Allow-Origin * always;
            # 允许跨域的请求方法
            add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, 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;
            }
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

    # Service2的配置
    server {
        listen       80;
        server_name  www.service2.com;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
            proxy_pass http://localhost:9096/;
            add_header Access-Control-Allow-Origin * always;
            add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS,PUT,DELETE' always;
            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;
            }
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108