httpd反向代理实践(二)

2023-10-15,

div.example { background-color: rgba(229, 236, 243, 1); color: rgba(0, 0, 0, 1); padding: 0.5em; margin: 1em 2em 1em 1em }
div.warning { border: 1px solid rgba(255, 0, 0, 1) }

在httpd反向代理实践(一)中,仅仅是使用了httpd来访问静态的资源文件,现在我们搭建真正的动态资源(基于servlet),然后看看反向代理中涉及到的 Content-Location和Location首部,以及cookie的domain和path时的情况。

首先是被代理端配置:

basePath : http://www.example.com:8080/hello

1. 重定向(Location首部)

@WebServlet("/dog")
public class Dog extends HttpServlet {
private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = request.getContextPath();
String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/"; //如果在重定向中不使用完全路径,那么重定向的Location内容就是/hello/cat,此时反向代理就无法正确的替换了。
//response.sendRedirect(path + "/cat"); //使用完全路径:http://www.example.com:8080/hello/cat,在反向代理中将被替换为 http://www.example1.com/tomcat/cat
response.sendRedirect(basePath + "cat");
}
}

2.设置cookie

@WebServlet("/SetCookie")
public class SetCookieServlet extends HttpServlet {
private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie nameCookie = new Cookie("name", "zhangsan");
//如果我们没有主动设置domain和path的话,那么即便没有ProxyPassReverseCookieDomain和ProxyPassReverseCookiePath指令也不会有问题。
nameCookie.setDomain(request.getServerName());
nameCookie.setPath(request.getContextPath()); response.addCookie(nameCookie); try(PrintWriter out = response.getWriter();){
out.print("set name cookie");
}
}
}

3. 获取cookie

@WebServlet("/GetCookie")
public class GetCookieServlet extends HttpServlet {
private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try(PrintWriter out = response.getWriter();){
Cookie[] cs = request.getCookies();
if(cs != null){
for(Cookie c : cs){
out.println(c.getName() + " --> " + c.getValue());
}
}
}
}
}

代理服务器端的配置:

ProxyPass "/tomcat" "http://www.example.com:8080/hello"
ProxyPassReverse "/tomcat" "http://www.example.com:8080/hello"
ProxyPassReverseCookieDomain "www.example.com" "www.example1.com"
ProxyPassReverseCookiePath "/hello" "/tomcat"
 Note: ProxyPassReverseCookieDomain 和 ProxyPassReverseCookiePath是被代理资源在前面,代理资源在后面。

按照上面配置搭建被代理环境,如果我们没有设置ProxyPassReverse 、ProxyPassReverseCookieDomain和ProxyPassReverseCookiePath的话,那么将无法正常重定向和存取cookie。

httpd反向代理实践(二)的相关教程结束。

《httpd反向代理实践(二).doc》

下载本文的Word格式文档,以方便收藏与打印。