proxy_set_header Host $host ;和proxy_set_header Host $proxy_host ;的比较

参考了:https://blog.csdn.net/felix_yujing/article/details/51682655
《精通Nginx 第二版》第4章 Nginx作为反向代理

nginx.conf的配置
server {
listen 80;
server_name www.lvzhongqian.com;

#charset koi8-r;

#access_log logs/host.access.log main;

location / {
#root html;
#index index.html index.htm;

#proxy_redirect off;
proxy_pass https://192.168.1.102:8443;
#proxy_set_header Host $host;
proxy_set_header Host $proxy_host;
}

#error_page 404 /404.html;

# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
上游应用的LoginFilter代码:
public class LoginFilter extends OncePerRequestFilter {
private static Logger LOGGER = Logger.getLogger(LoginFilter.class);

@Override
protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response, FilterChain filterChain)throws ServletException,IOException {

if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
throw new ServletException(“OncePerRequestFilter just supports HTTP requests”);
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;

LOGGER.info(“remote addr is: ” + httpRequest.getRemoteAddr());//getRemoteAddr(): Returns the Internet Protocol (IP) address of the client or last proxy that sent the request.
Enumeration parameterNames = httpRequest.getParameterNames();
while (parameterNames.hasMoreElements()) {
LOGGER.info(“Parameter Name: ” + parameterNames.nextElement().toString());
}
LOGGER.info(“Header Host: ” + httpRequest.getHeader(“Host”));

HttpSession session = httpRequest.getSession();
SysUser user = (SysUser) session.getAttribute(“user”);
String servletPath = httpRequest.getServletPath();
if (null == user
&& (!”/gotoLogin”.equals(servletPath) && !”/login”.equals(servletPath))) {
httpResponse.sendRedirect(“/gotoLogin”);
} else {
filterChain.doFilter(httpRequest, httpResponse);
}

}

}

a. proxy_set_header Host $host;

1
http://www.lvzhongqian.com/gotoLogin 执行登录后,结果如下:
2
3
因为在location里面添加一条 proxy_set_header Host $host; 配置时,则不改变请求头的值,所以转发到上游服务器的时候,请求头的Host信息还是Nginx中配置的虚拟服务器的server_name(保持的是域名部分,协议还是proxy_pass中配置的https协议).

b.proxy_set_header Host $proxy_host;

1). proxy_redirect on;

4
当Host设置为$proxy_host时,则向上游服务器发请求时会重新设置请求头的host信息为proxy_pass中的域名/IP:port信息 (即所请求的上游服务器本身的域名/IP:port信息)
http://www.lvzhongqian.com/gotoLogin 执行登录后,结果如下:
5
默认proxy_redirect on;,Nginx服务器响应客户端请求时,重写了上游服务器响应时的Location和Refresh头的。

6
2). proxy_redirect off;

7

http://www.lvzhongqian.com/gotoLogin 执行登录后,结果如下:

8

proxy_redirect off;,Nginx服务器响应客户端请求时,保持上游服务器响应时的Location和Refresh头的。

9

Posted in IT

Author: ilvzhongqian

寄意寒星荃不察,我以我血荐轩辕