Spring Boot 使用 Tomcat 作為容器時訪問根 context-path 302分析
起因是安全團隊反饋了一個漏洞,說通過公網域名訪問內網中的一個SpringBoot服務的根路徑,原本是域名的url變成了服務的內網的ip。
簡略版的網絡拓撲如下:

SpringBoot版本:2.2.5.RELEASE
server.servlet.context-path=/demo
通過域名訪問的url如下:
https://domain.cn/demo
訪問之后url轉變為:
http://10.x.1/demo/
因為網關后面的SpringBoot服務在多個機器部署,轉變后的url會變成其中的一臺服務器的ip。
在nginx機器上看了下日志,發現請求有一個302重定向的過程,然后變成了SpringBoot的404頁面,因為根路徑沒有對應的handler處理。
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Fri Apr 10 23:59:59 CST 2025
There was an unexpected error (type=Not Found, status=404).
No message available
測試環境,在Chrome中打開F12調試模式,在Network下開啟Preserve log,通過SpringBoot服務所在機器的ip和端口直接訪問服務的根路徑,同樣有一個302重定向的過程
http://10.x.1/demo
會轉變為
http://10.x.1/demo/
url在302重定向后,url后面拼接了一個 /
懷疑是不是SpringBoot有什么特殊處理,SpringBoot中是通過org.springframework.web.servlet.DispatcherServlet:doDispatch方法來分發處理請求的,本地調試項目發現doDispatch方法會進入兩次,DispatcherServlet上面是tomcat容器了,看樣子是容器里了,往上回溯調用鏈發現org.apache.catalina.mapper.Mapper:internalMapWrapper方法里有一段代碼有關于重定向的邏輯,代碼如下:
if(mappingData.wrapper == null && noServletPath &&
contextVersion.object.getMapperContextRootRedirectEnabled()) {
// The path is empty, redirect to "/"
path.append('/');
pathEnd = path.getEnd();
mappingData.redirectPath.setChars
(path.getBuffer(), pathOffset, pathEnd - pathOffset);
path.setEnd(pathEnd - 1);
return;
}
意思就是如果請求的路徑是 "" ,那么將重定向到 / ,項目的 server.servlet.context-path=/demo,那么訪問根路徑,后面不加其它的url,正好就走到了這一個邏輯里面,看代碼邏輯是有一個參數可以控制是否重定向的:mapperContextRootRedirectEnabled,這個是org.apache.catalina.core.StandardContext類中的一個配置參數,可以通過配置來修改
server.tomcat.redirect-context-root
貼一下它的注釋:
Determines if requests for a web application context root will be
redirected (adding a trailing slash) by the Mapper. This is more
efficient but has the side effect of confirming that the context path is
valid.
修改參數的值為false,重啟項目再次訪問,不再出現302,而是直接到了404頁面
server.tomcat.redirect-context-root=false
如果項目的context-path是 / 沒有302重定向的過程。
有項目使用了undertow作為容器,但是看了下undertow的代碼,發現沒有提供類似的參數,后面寫一篇文章來記錄使用undertow作為容器時出現這樣情況的解決方案。
tomcat作為老牌的容器,相較undertow還是有更多靈活的配置選項。
本文來自博客園,作者:杜勁松,轉載請注明原文鏈接:http://www.rzrgm.cn/imadc/p/18820909

浙公網安備 33010602011771號