Nginx redirect without port

cloudflarenginxredirectvarnish

I have an issue with 301 redirects in Nginx. It always redirects to a URL with it's local port.

Situation is as follows: Site is running through Cloudflare, full https. CF sends http requests to the server where varnish accepts them. Varnish then passes the request on to nginx which handles the rest together with FPM.

Nginx is running on port 8080. I create a 301 redirect in Nginx like I usually do:

location = /url1 {
  return 301 /url2;
}

Nginx then redirects to the URL, but adds the original hostname & port it's running in (8080). So I set port_in_redirect to off in the server config. That works half. It'll redirect an http URL to https (without mentioning port 8080). It'll redirect an https URL to http though, loop.

How can I make sure that that doesn't happen? I wonder if it's possible to know the scheme that Cloudflare is servicing the request on as well.

Best Answer

Try to add absolute_redirect off to your location block

location = /url1 {
  absolute_redirect off;
  return 301 /url2;
}