|
|
nginx.conf配置:
& d1 `& D- T' I; O! N+ m! d6 k" ^' a i
location / { " n$ C5 u. P A5 t
proxy_pass http://127.0.0.1:8081/myweb/;
( v2 ~) n1 V; f& N) } proxy_redirect off; 6 T# R+ C* ^7 q) Q; k
proxy_set_header Host $host; ) ]+ {0 D1 |0 f5 ~8 x
proxy_set_header X-Real-IP $remote_addr; E7 U; h- ~: A) h7 S ^
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
- m8 i0 u& |( ~8 L5 q3 Q}
% r9 I2 V. I- k* `' s4 N0 c( m- \1 t, k ]8 r8 M# H
后端获取方式:
9 |& s% ^/ C# h
7 c5 H0 ^( S5 H$ A( d: J/ H/*** 0 ~' L+ `8 e; [
* 获取客户端IP地址;这里通过了Nginx获取;X-Real-IP,
4 {0 h0 d- r1 m$ a9 b2 o * @param request
- v0 L f8 ~5 ~+ V% [/ i* ~ * @return $ m# W, a r! {* v7 o+ A" o* y
*/ 6 r6 _8 s7 t) Z: h, l; Y$ k5 \; ?
public static String getClientIP(HttpServletRequest request) { ; u7 V% l! G3 l. `5 X9 {2 M9 m! a5 F
String fromSource = "X-Real-IP";
: J, p4 A& _$ x, [( J% O& z String ip = request.getHeader("X-Real-IP");
0 a/ k0 O% E5 S8 d$ r if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
( X8 M* `2 w7 h# p9 i9 n, u ip = request.getHeader("X-Forwarded-For");
" H9 d1 h6 d0 k& n; g fromSource = "X-Forwarded-For";
. X+ P+ Q& w8 v9 a) E: A }
+ I0 K+ d# ^+ {% P, S if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
% N3 F9 w$ }' p+ m$ V ip = request.getHeader("Proxy-Client-IP"); 9 V$ o/ J0 m( m; i1 E
fromSource = "Proxy-Client-IP"; j& Y( b9 a- U1 U2 d
} ( Z6 x. c: j: X& E. P+ {! E
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
+ Y( p# p1 W6 ^+ w b- V ip = request.getHeader("WL-Proxy-Client-IP"); 8 y1 }7 X# v5 m0 w; g
fromSource = "WL-Proxy-Client-IP"; , F4 [ {6 C" G, v/ }* |) {
} 7 w0 J1 W {, a) K
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ! d% D) V' {) W1 Z/ n4 C) Z
ip = request.getRemoteAddr();
! b$ @) I0 p- A7 e fromSource = "request.getRemoteAddr";
% V' m A) F$ J) A. b8 A. N, l) f8 k }
) u, \3 P+ H( H, K) ?, R appLog.info("App Client IP: "+ip+", fromSource: "+fromSource);
! X% g) A( y% Q return ip; $ B) G0 C8 B Z4 K- q
}
( k& w: o% f: N$ A" D2 [- M: G! o$ K
" O2 ^7 l% z V这样就不会一直获取的是服务器的Ip了。
) l: p- Y& n. h( t4 `" T7 o- A
9 e9 R+ ^2 |% w7 ]2 a9 l% p$ N* K$ u- ^/ a
|
|