Redirect loop on reverse proxy

52 Views Asked by At

I have two nginx websites (let's call them A, B) on different ports of the same machine, and I'm trying to proxy A to B with a specific host header. The request is initiated by a cloudflare worker, so the host needs to be modified.

Scenario is:

  • User opens my.website.com
  • Cloudflare worker loads website-a.website.com:65112, but can't override the host header
  • nginx handles request for webiste A
  • nginx proxies the request to website B on port 65113, changing the host header back to my.website.com - this is crucial, as website B needs the host header to be the original host

This is my current configuration:

# website A
server {
  listen                  65112;
  client_max_body_size    10G;

  location / {
    proxy_pass            http://127.0.0.1:65113;
    proxy_redirect        off;
    proxy_set_header      Host my.website.com;
    proxy_read_timeout    1800;
    proxy_connect_timeout 1800;
    proxy_send_timeout    1800;
    send_timeout          1800;
  }
}

# website B
server {
  listen               65113;
  client_max_body_size 10G;
  index index.php;

  location / {
    root /var/www/html/nextcloud;
    try_files $uri /index.html index.php;
  }

  location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
  }
}

The worker code is pretty simple:

export default {
  async fetch(request) {
    return fetch(
      `http://website-a.website.com:65112`,
      request,
    );
  },
};

What I expect:

  • User opens my.website.com
  • Worker loads website-a.website.com:65112
  • nginx reverse-proxies to 127.0.0.1:65113 with correct Host header
  • website B answers correctly and the webpage is displayed

What happens instead:

  • User opens my.website.com
  • there is an infinite redirect loop on my.website.com

If I remove the proxy_pass directive from website A, my.website.com correctly displays nginx default page, so this leads me to think that the issue is with the proxy itself.

Is there a way to fix this?

0

There are 0 best solutions below