Nginx的配置笔记

配置反向代理并支持跨域请求

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
location ^~ /api/ {
# Check if the origin of th request
set $cors 'on';

if ($request_method = OPTIONS) {
set $cors "${cors}_options";
}

# Allow CORS on preflight request
if ($cors = 'on_options') {
add_header 'Content-Length' 0;
add_header 'Content-Type' 'text/plain; charset=utf-8';
# 跨域时允许的来源地址
add_header 'Access-Control-Allow-Origin' "$http_origin";
# 跨域时允许的请求类型
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
# 跨域时允许提交的请求头字段
add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept';
return 204;
}

# Proxy pass to upstream
proxy_pass http://192.168.1.100:8080;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;

# Allow CORS on other requests after returning from the upstreams
if ($cors = 'on') {
add_header 'Access-Control-Allow-Origin' "$http_origin";
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Origin, X-Requested-With, Content-Type, Accept';
}
}

参考地址:

  1. https://enable-cors.org
  2. https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
  3. https://blog.boatswain.io/post/setup-cors-in-nginx-with-proxypass-upstream/