nginx作为服务器分发请求与静态代理,负载均衡的神器,一些必备的使用技巧,是需要我们关注的
1.java后端获取ip的代码片段
//1.通过nginx中获取ip地址
protected String getIp() {
String ip = request.getHeader("X-Real-IP");
if(StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("x-forwarded-for");
}
if(StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if(StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
2.ngxin配置ip策略
server代码段,
一层nginx代理
添加以下内容:
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Real-Port $remote_port;
proxy_set_header X-Forwarded-For $remote_addr;server代码段,
多层反向代理
下,最外层ngxin添加一下内容:
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Real-Port $remote_port;
proxy_set_header X-Forwarded-For $remote_addr;非最外层nginx,可以添加一下内容:
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;示范代码,展示本地使用nginx的代理分发
server {
listen 8880;
server_name leanboot.com;
#charset koi8-r;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Real-Port $remote_port;
proxy_set_header X-Forwarded-For $remote_addr;
location / {
proxy_pass http://127.0.0.1:8080/;
}
location /files-server/ {
proxy_pass http://127.0.0.1:8088/;
}
}