Warm tip: This article is reproduced from serverfault.com, please click

How can I prevent ProxyPreserveHost from redirecting indefinitely?

发布于 2020-12-03 10:17:50

I'm trying to have two subdomains, my.domain.com and foo.my.domain.com, both redirect to the same directory of my Apache2 server (127.0.0.1/my/).

However, I want the scripts there to be able to tell from which domain the request came from. The way I see it, there would be two ways to do that:

  • Using a RewriteRule to add ?foo=bar at the end of every request that contains .php, but that sounds quite dirty
  • Use ProxyPreserveHost to indicate to the PHP script what the original domain is, which sounds more normal and sane.

However, the second I enable ProxyPreserveHost I'm getting a neverending 301 redirection loop. This is the virtual host configuration:

My.Domain.com:

<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName my.domain.com

    ProxyPass / http://127.0.0.1/my/
    ProxyPassReverse / http://127.0.0.1/my/
    ProxyRequests Off

    SSLCertificateFile /etc/letsencrypt/live/my.domain.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/my.domain.com/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>

Foo.My.Domain.Com:

<IfModule mod_ssl.c>
<VirtualHost *:443>
    ServerName foo.my.domain.com

    ProxyPass / http://127.0.0.1/my/
    ProxyPassReverse / http://127.0.0.1/my/
    ProxyRequests Off
    ProxyPreserveHost On      # creates 301 loop!

    SSLCertificateFile /etc/letsencrypt/live/my.domain.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/my.domain.com/privkey.pem
    Include /etc/letsencrypt/options-ssl-apache.conf
</VirtualHost>
</IfModule>

Note: I've also tried to put ProxyPassReverse / https://foo.my.domain.com/ in the second domain foo.domain.com, but it didn't change anything.

How can I preserve the host without causing a redirect loop?

Questioner
Rackover
Viewed
0
Rackover 2020-12-07 22:18:23

Found it:

$_SERVER["HTTP_X_FORWARDED_HOST"] contains the hostname, so foo.my.domain.com in my case. I did not need UseCanonicalName nor ProxyPreserveHost in the end.