文章目录
一、配置总览
upstream example_server {
server xxx.xxx.xxx.xxx:8080;
}
server {
listen 80;
server_name www.example.com;
if ($http_cookie !~* ".*_lin.*") {
rewrite ^/?$ http://redirect_server;
}
access_log /var/log/nginx/example.access.log main;
error_log /var/log/nginx/example.error.log error;
client_max_body_size 10m;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
location ~* (/v1/.*) {
proxy_pass http://example_server$1?$args;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host:$server_port;
}
}
二、填坑记录
1. 使用upstream定义服务器别名时访问失败
解决方法:添加下面两行配置
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host:$server_port;
2. 通过代理访问接口时参数丢失
解决方法:在原配置后添加
?$args
原配置:proxy_pass http://example_server$1
修改后:proxy_pass http://example_server$1?$args;
3. 上传文件时返回码为413:Request Entity Too Large
解决方法:在子配置的
server
配置中指定client_max_body_size
server {
client_max_body_size 10m;
}
4. 根据cookie匹配重定向规则
解决方法:if ($http_cookie !~* “.*_lin.*”) { }
# 如果cookie中不包含"_lin"(不区分大小写),则url为"http://www.example.com"的请求将被重定向到"http://redirect_server"
if ($http_cookie !~* ".*_lin.*") {
rewrite ^/?$ http://redirect_server;
}
5. 跨域配置
解决方法:在server层中添加以下配置
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;
}
注:当请求成功时,HTTP CODE 为200。而请求失败时HTTP CODE 为400, 此时add_header ‘Access-Control-Allow-Origin’ ‘*’ 配置无效!设置无论HTTP CODE 为何值时都生效需要加 always 。nginx版本>1.7.5时候无须加always。
6. 浏览器提示"ERR_UNSAFE_PORT"
解决方法:更换端口
这个错误产生的原因是chorme浏览器有自己的默认非安全端口,若访问这些端口就会出现这个错误,并且所有采用chorme内核的浏览器都会这样。