问题原文
原帖链接 · 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.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
