让Servlet通过Nginx反向代理抛出错误404?

时间:2014-04-05 18:38:08

标签: tomcat servlets nginx proxy

如何让我的Servlet抛出将由我的Nginx代理重定向的错误404?

它适用于Nginx抛出的404s。但是如果请求被代理到Tomcat,则错误404页面来自Tomcat而不是Nginx。

我可以以某种方式返回错误404,然后由Nginx重定向拾取吗?或者我是否需要在web.xml中配置并行404错误页面?

我的nginx配置中包含以下内容:

location ~ \.do$ {
    proxy_pass              http://127.0.0.1:8080;
    proxy_set_header        Host $http_host;
    proxy_set_header        X-Real-IP $remote_addr;
    proxy_set_header        X-Forwarded-Host $host;
    proxy_set_header        X-Forwarded-Server $host;
    proxy_set_header        X-Forwarded-Proto $scheme;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
}

error_page  404 = @page-not-found;
location @page-not-found {
    rewrite  .*  /search?status=page-not-found permanent;
}

和servlet一样:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {       
    String handle = request.getParameter("handle");     
    Page page = pageDao.getPageByHandle(handle);        
    if(page.getId()!=null){
        request.setAttribute("page", page);
        request.getRequestDispatcher("/site/page.jsp").forward(request , response); 
    }
    response.sendError(HttpServletResponse.SC_NOT_FOUND);
}

1 个答案:

答案 0 :(得分:0)

似乎你只需在nginx配置中添加proxy_intercept_errors on ...

如:

proxy_intercept_errors on;

error_page  404 = @page-not-found;
location @page-not-found {
    rewrite  .*  /search?status=page-not-found permanent;
}