Redirect loop when using Varnish + Nginx (HTTPS)

2019-08-12 00:49发布

问题:

I am trying to use Varnish and Nginx in a WP site using HTTPS.

Everything is working fine with cached files but when Varnish discover something it shouldn't cache, it sends it back to Nginx. At this point, Nginx is sending the HTTPS request to Varnish again causing the infinite loop.

I have tried a lot of things and searched over the Internet a lot but nothing has worked so far.

This is an example of something Varnish is sending back:

if (req.url ~ "/wp-(login|admin|cron)") {
        # Don't cache, pass to backend
        return (pass);
}

And this is the Nginx location block which deals with 433:

location / {
    # Send request to varnish
    proxy_pass  http://127.0.0.1:8888;
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Port 443;
    proxy_set_header Host $host;
}

I guess that Varnish is sending with the return(pass) the data back to Nginx, but I don't now how to render that data using another location block.

How can I catch in Nginx the request which is coming from Varnish and distinguish between that and the requests which are coming from the regular 433 port?

Thanks in advance!

回答1:

I found the problem: HHVM.

I created another backend without HHVM on Nginx (port 9433) and did the following in Varnish:

backend no_hhvm {
   .host = "127.0.0.1";
   .port = "9433";
}

And then...

# Either the admin pages or the login
if (req.url ~ "/wp-(login|admin|cron)") {
        # Don't cache, pass to backend
        set req.backend = no_hhvm;
        return (pass);
}

So when the page is not cached it goes to the port 9433 which doesn't use HHVM.

Working great now.



回答2:

This might have been caused by hhvm expecting the request over port 443(https) resulting in a redirect to https that ends up in varnish again.



回答3:

Try adding:

fastcgi_param HTTPS on;

to the location block with your fastcgi_pass to php. I had this exact problem here: https://serverfault.com/questions/670620/nginx-varnish-hhvm/670857