如何设置 apache2 RequestHeader only for a Location?

问题描述 投票:0回答:1

我想设置一个

RequestHeader
X-Forwarded-Prefix
,但只适用于特定路径。

伪代码:

<VirtualHost *:443>
    <Location /api1>
        ProxyPass https://host/api1 http://localhost:8080
        ProxyPassReverse https://host/api1 http://localhost:8080

        RequestHeader set X-Forwarded-Prefix "/api1"
    </Location>

    <Location /api2>
        ProxyPass https://host/api2 http://localhost:8080
        ProxyPassReverse https://host/api2 http://localhost:8080

        RequestHeader set X-Forwarded-Prefix "/api2"
    </Location> 
</VirtualHost>

这可能吗?

如果没有,我如何根据重定向的上下文路径(此处:/api1 和 /api2)传递不同的

X-Forwarded-Prefix
值?

apache2 reverse-proxy
1个回答
0
投票

以下解决方案对我有用,当我想配置 Apache2 Web 服务器以将原始子目录前缀从转发主机传递到请求标头中的目标主机时。

<VirtualHost *:80>
    ...

    ProxyPass /subdirName1 http://otherHost1:port1
    ProxyPassReverse /subdirName1 http://otherHost1:port1
    <Location /subdirName1 >
        RequestHeader add x-forwarded-prefix "/subdirName1"
    </Location>

    ProxyPass /subdirName2 http://otherHost2:port2
    ProxyPassReverse /subdirName2 http://otherHost2:port2
    <Location /subdirName2 >
        RequestHeader add x-forwarded-prefix "/subdirName2"
    </Location>

    ...
</VirtualHost>

我特别需要它来让网页从正确的地址加载依赖项,例如 CSS 和 JS,例如:不是从

/css/...
而是从
${forwardedPrefix}/css/
(其中
forwardedPrefix
设置为
subdirName1
,取自标题。

这之所以成为可能,是因为服务器

otherHost1
(
port1
) 接收到的请求标头包含变量
x-forwarded-prefix
,其值为
/subdirName1
,因此目标服务可以重新构建其基于
/
的 URL相应地。

这适用于所有 HTTP 方法,

GET
POST
PUT
DELETE

© www.soinside.com 2019 - 2024. All rights reserved.