httpd反向代理实践(二)

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

首先是被代理端配置: 服务器

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

1. 重定向(Location首部)dom

@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.设置cookiespa

@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());
                }
            }
        }
    }
}

 

代理服务器端的配置:code

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。blog

相关文章
相关标签/搜索