大网数据广告活动
服务器运维问答

Apache behind nginx reverse proxy, setting the correct Host header

· 52CE 我爱测

I'm running my application using Apache in a Docker container. I have nginx acting as a reverse proxy running in another Docker container which has Apache as its upstream. I'm using the proxy_pass directive for this. Apache runs …

问题原文

原帖链接 · fairport · CC BY-SA 4.0

I'm running my application using Apache in a Docker container. I have nginx acting as a reverse proxy running in another Docker container which has Apache as its upstream. I'm using the proxy_pass directive for this.

Apache runs in the URL https://example-8gnm1aqrns-lz.a.run.app Nginx runs in the URL http://example.com

The whole thing is running on Google Cloud Run and the problem is that Google Cloud Run assigns every service an URL and it uses the Host header to differentiate between the applications so I'm forced to send the header Host: example-8gnm1aqrns-lz.a.run.app when connecting to the upstream using nginx so the request routes correctly.

This causes a problem with my application because it thinks it's running in the URL https://example-8gnm1aqrns-lz.a.run.app and not http://example.com.

Is it possible to use some Apache .htaccess configuration to overwrite the Host header based on the X-Forwarded-Host sent by nginx?

社区高分解答

原帖链接 · fairport · CC BY-SA 4.0

I solved this issue by defining a new environment variable called APP_HOST in the Google Cloud Run control panel and setting it to example.com.

Then I added the following configuration to the .htaccess file in the document root:

<IfModule mod_env.c>
    PassEnv APP_HOST
</IfModule>

<IfModule mod_headers.c>
    RequestHeader set Host %{APP_HOST}e env=APP_HOST
</IfModule>

This allowed me to override the Host header from example-8gnm1aqrns-lz.a.run.app to example.com based on the environment variable APP_HOST.

I could have of course hardcoded the hostname but I think that using an environment variable gives you more flexibility if you want to use the same .htaccess file in different contexts, such as on a staging server.

Edit

Here's how you can solve this using X-Forwarded-Host, for example if you run virtual hosts and you need to site to be accessible from multiple domains

<IfModule mod_setenvif.c>
    SetEnvIf X-Forwarded-Host (.*) REAL_HOST_HEADER=$1
    <IfModule mod_headers.c>
        RequestHeader set Host "%{REAL_HOST_HEADER}e"
    </IfModule>
</IfModule>

This will grab the header from X-Forwarded-Host and set the Host header based on the value.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2021-10-10)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。