gpt4 book ai didi

apache - 在反向代理 (ProxyPass) 后面的 Mojolicious 中配置带有前缀的 URL

转载 作者:行者123 更新时间:2023-12-02 05:56:36 24 4
gpt4 key购买 nike

我正在寻找一种可靠的方法来配置 Mojolicious 在/app 下的 Apache 反向代理后面运行,以便 url_for('/​​foo') 实际上返回 /app/foo 而不是 /foo (否则所有链接都会损坏)。

documentation显示/下所有内容的反向代理示例。但这不是我需要的,因为应用程序应该位于/app 下。
ProxyPass/http://localhost:8080/ 转换为 ProxyPass/app http://localhost:8080/ 将导致 /app 出现问题应用程序生成的所有 URL 中都会缺少 code> 前缀。

该文档还有 section on rewriting ,其中有一个 before_dispatch Hook 的示例,它将获取请求 url 的第一部分并将其用作基础。这需要将前缀附加到 Apache 配置中的 ProxyPass url(ProxyPass/app http://localhost:8080/app/ ,末尾带有斜杠),这似乎没有提及页面,但也许不需要(“将第一部分和斜杠从路径移动到基本路径”),因为它很明显。这使得调用 http://localhost/app/page 成为可能,它会变成 http://localhost:8080/app/page (“app”被删除钩子(Hook)),其中 url_for('/​​foo') 将返回 '/app/foo' (http://localhost/app/foo),因此链接将是正确的(ProxyPass 规则中没有尾部斜杠,这将导致 /apppage/foo)。

但是,在此示例中,网址修改始终在生产模式下进行(if app->mode eq 'product')。因此,直接调用后端服务器(http://localhost:8080/testpage)将不再起作用,因为所有网址都会被破坏。

所以我想,我应该检查是否设置了 X-Forwarded-For header (通过 mod_proxy_http),该 header 始终为反向代理请求设置。自从 Apache mod_proxy documentation提到此 header 可能已在客户端请求中设置(并最终包含多个值),我会首先从请求中将其删除 - 因为发送此 header 的客户端不应导致 url 基址修改。

Apache 虚拟主机配置:

# ProxyPreserveHost: Mojo::URL::to_abs() not 127.0.0.1
ProxyPreserveHost On
<Location "/app/">
# ProxyPass: prefix pass-thru
ProxyPass http://localhost:3000/app/
# RequestHeader: must not be set externally
RequestHeader unset X-Forwarded-For
</Location>

Hook Mojolicious 启动():

$self->hook('before_dispatch' => sub {
my $c = shift;
my $behind_proxy = !!$c->req->headers->header('X-Forwarded-Host');
if ($behind_proxy) {
push @{$c->req->url->base->path->trailing_slash(1)},
shift @{$c->req->url->path->leading_slash(0)};
$c->req->url->path->trailing_slash(0) # root 404
unless @{$c->req->url->path->parts};
}
});

这似乎有效...

问题:我的方法在“现实世界”中可靠吗还是有缺陷?

编辑:
通过反向代理请求根地址 (http://localhost:3000/app/) 总是会导致错误 404。因此,我添加了两行以在这种情况下关闭尾部斜杠。由于我在文档中找不到,可能有更好的方法。

最佳答案

您需要在before_dispatch钩子(Hook)中为每个请求url设置基本路径

$app->hook(before_dispatch => sub {
my $c = shift;
$c->req->url->base->path('/app/');
});

示例:

use Mojolicious::Lite;

app->hook(before_dispatch => sub {
shift->req->url->base->path('/app/');
});


get '/' => sub {
my $c = shift;
$c->render(text => $c->url_for('test'));
};

get '/test/url' => sub { ... } => 'test';

app->start;

结果:

$ curl 127.0.0.1:3000
/app/test/url

关于apache - 在反向代理 (ProxyPass) 后面的 Mojolicious 中配置带有前缀的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23571608/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com