当在反向代理(在我的例子中是 nginx)后面的服务器上使用时,我很难让 Thymeleaf 正确形成相对 URL。
假设我在 nginx 中有以下位置:
location /app {
proxy_pass http://10.0.0.0:8080;
}
我有以下 Thymeleaf 3 页面 (index.html
):
<html xmlns:th="http://www.thymeleaf.org">
<head>
<link rel="stylesheet" th:href="@{/css/some.css}" />
</head>
<body>
Hello world!
</body>
</html>
所使用的服务器是一个嵌入式 Tomcat 服务器(Spring boot),在上下文 /
中运行。
当我向 http://example.com/app
发送请求时,我会收到 index.html
页面作为响应。但是css无法检索,因为在Thymleaf模板中构造URL时,它使用了tomcat服务器的上下文路径,即/
。 index.html
中构造的 url 如下所示:
http://example.com/css/some.css
这显然会导致 404 未找到。 URL 需要按如下方式构成:
http://example.com/app/css/some.css
我需要配置什么才能让 Thymeleaf 将 URL 形成为 http://example.com/app/css/some.css
?我宁愿不在任何地方为某些配置文件或类似的东西硬编码基本 URL。我想我需要在 nginx 配置中添加一些东西,但我不确定具体是什么。
最佳答案
正确的解决方案是通知 springboot 应用程序它正在代理后面。
尝试将 nginx 配置扩展为如下内容:
location /app {
proxy_pass http://10.0.0.0:8080;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host:$server_port;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Prefix /app;
}
要了解使用 Forwarded header (几年来的标准),请查看 https://www.nginx.com/resources/wiki/start/topics/examples/forwarded/ 该主题的 spring 文档中存在一些不匹配,您可以查看一些问题/项目以获取更多信息:
- 很有帮助的“插件”https://github.com/qaware/x-forwarded-filter
- > https://github.com/spring-projects/spring-boot/issues/15046
- > https://github.com/spring-projects/spring-hateoas/issues/862
- > https://github.com/spring-projects/spring-security/issues/7081
PS:如果您正在测试您的 springboot 应用程序配置,可以方便地使用 cURL 在本地进行,而无需使用 nginx。要模拟来自代理的请求 header ,您可以使用此命令:
curl -i http://localhost:8080 \
-H 'X-Forwarded-Host: example.com' \
-H 'X-Forwarded-Port: 443' \
-H 'X-Forwarded-prefix: /myDevelApp' \
-H 'X-Forwarded-proto: https'
或使用标准化 header :
curl -i http://localhost:8080 \
-H 'X-Forwarded-prefix: /myDevelApp' \
-H 'Forwarded: for=123.333.333.333;host=example.com;proto=https'
关于spring - 反向代理后面的 Thymeleaf 模板(在 Spring 引导应用程序中)未正确形成 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44022686/