处理跨域
忽略上游头部
# 忽略上游的 Access-Control-Allow-Origin 头部
proxy_hide_header Access-Control-Allow-Origin;
支持全部来源域名
# 在 Nginx 中添加或覆盖 Access-Control-Allow-Origin 头部
# add_header Access-Control-Allow-Origin "你的值"; # 注意:一定要是具体的域名,不能是*
add_header Access-Control-Allow-Origin $http_origin; # 这样是支持所有来源
只支持某几个域名
set $cors_origin "";
if ($http_origin ~* "^http://foo.baidu.com$") {
set $cors_origin $http_origin;
}
if ($http_origin ~* "^http://bar.baidu.com$") {
set $cors_origin $http_origin;
}
add_header Access-Control-Allow-Origin $cors_origin;
处理路径对应
使用rewrite重写路径
rewrite ^/testapi/api/(.*)$ /api/$1;
# 或者是 rewrite ^/testapi/(.*)$ /$1;
proxy_pass https://www.baidu.com;
# 或者是 proxy_pass https://www.baidu.com/;
其他鉴权请求头
cookie部分
set $domain "";
if ($host ~* "(.*)(\..*)(\..*)" ) {
set $domain $2$3;
}
proxy_cookie_domain .baidu.com $domain;
proxy_set_header Cookie $http_cookie;
proxy_pass_header Set-Cookie;
其他请求头
proxy_set_header Host www.baidu.com;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Referer "";
完整location
location /testapi {
rewrite ^/testapi/api/(.*)$ /api/$1;
if ($request_method = 'OPTIONS') {
return 204;
}
proxy_pass https://www.baidu.com;
set $domain "";
if ($host ~* "(.*)(\..*)(\..*)" ) {
set $domain $2$3;
}
proxy_cookie_domain .baidu.com $domain;
proxy_set_header Cookie $http_cookie;
proxy_pass_header Set-Cookie;
proxy_set_header Host www.baidu.com;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Referer "";
proxy_hide_header Access-Control-Allow-Origin;
set $cors_origin "";
if ($http_origin ~* "^http://foo.baidu.com$") {
set $cors_origin $http_origin;
}
if ($http_origin ~* "^http://bar.baidu.com$") {
set $cors_origin $http_origin;
}
add_header Access-Control-Allow-Origin $cors_origin;
}