Nginx + Varnish Wrong Port With Redirects

I recently switched my blog and many of my sites over to a new server stack, with Varnish running in front of Nginx + PHP-FPM. I noticed an issue however.

When requesting a path like:, I was being redirected to This alone took me a few minutes to discover, as the original problem manifested as the page taking forever to load. That turned out to be because that added port number doesn’t work with CloudFlare, so it was timing out eventually.

The problem here is that Nginx with my try_files rules will add a trailing slash to directories, but the HTTP redirect included the port that nginx was listening on. I confirmed that it was Nginx causing the redirect and not Varnish by inspecting the log files.

Knowing this, I did some research and found an option that will disable adding the port to Nginx redirects. I put this in my http block, which now looks like this:

http {
  port_in_redirect off;

After a quick nginx reload, my problem was solved 🙂

Leave a Reply