反向代理后面的Thymeleaf模板(在Spring Boot应用程序中)无法正确形成url [英] Thymeleaf template (in Spring boot application) behind reverse proxy not forming url's correctly

查看:445
本文介绍了反向代理后面的Thymeleaf模板(在Spring Boot应用程序中)无法正确形成url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当在逆向代理(在我的情况下为nginx)后面的服务器上使用Thymeleaf时,要使Thymeleaf正确地形成相对URL有点麻烦.

I have some trouble getting Thymeleaf to form relative URL's correctly when it is used on a server behind a reverse proxy (nginx in my case).

假设我在nginx中具有以下位置:

Let's say I have the following location in nginx:

location /app {
    proxy_pass http://10.0.0.0:8080;
}

我有以下Thymeleaf 3页面(index.html):

I have the following Thymeleaf 3 page (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服务器(春季启动),在上下文/上运行.

The server used is an embedded Tomcat server (Spring boot), running at context /.

当我向http://example.com/app发送请求时,我得到index.html页面作为响应.但是,无法检索css,因为在Thymleaf模板中构造URL时,它将使用tomcat服务器的上下文路径,即/. index.html中的构造的URL如下所示:

When I send a request to http://example.com/app, then I get the index.html page as response. The css cannot be retrieved however, because when the URL is constructed in the Thymleaf template, it uses the context path of the tomcat server, which is /. The constructed url in the index.html looks as follows:

http://example.com/css/some.css

这显然会导致找不到404. URL的格式如下:

This obviously results in a 404 not found. The URL needs to be formed as follows:

http://example.com/app/css/some.css

我需要配置什么以使Thymeleaf以http://example.com/app/css/some.css的形式形成UR​​L?我宁愿不在任何地方为某些配置文件或类似内容对基本URL进行硬编码.我想我需要在nginx配置中添加一些内容,但是我不确定到底是什么.

What do I need to configure to let Thymeleaf form the URL as http://example.com/app/css/some.css? I would rather not hardcode the base URL anywhere for certain profiles or something like that. I think I need to add something to the nginx configuration, but I'm not sure what exactly.

推荐答案

最终将Tomcat服务器的上下文与所需的Nginx位置进行匹配.根据上面的示例,上下文将设置为"/app".

Ended up matching the context of the Tomcat server to the desired Nginx location. According to above example, the context would be set to '/app'.

我在application.yml中设置了应用程序上下文属性:

I set the application context property in the application.yml:

server:
  servlet:
    contextPath: /app

这篇关于反向代理后面的Thymeleaf模板(在Spring Boot应用程序中)无法正确形成url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆