Magento 2 – Fix Varnish with NGINX SSL Proxy 502 Error

magento2nginxsslvarnish

I am trying to setup an nginx backend with Varnish and magento 2.3.2.
To do that the flow would be:
Port 80 is forwaded to 443.
443 proxypass to Varnish
Listener on 8080.

Here is the nginx config for port 80:

upstream fastcgi_backend {
# Socket path
  server unix:/run/php/php7.2-fpm.sock;
}

server {
    listen 80;
    server_name magento-test.example.com;

    location ^~ /.well-known/acme-challenge/ {
      allow all;
      root /var/lib/letsencrypt/;
      default_type "text/plain";
      try_files $uri =404;
    }
    return 301 https://magento-test.example.com$request_uri;
}

Then the listener on port 443 with proxypass:

server {
    listen 443 ssl http2;
    server_name magento-test.example.com;

    ssl_certificate ...
    ssl_certificate_key ...
    ssl_trusted_certificate ...
    ssl_dhparam /etc/ssl/certs/dhparam.pem;

    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers 'AES128+EECDH:AES128+EDH:!aNULL';
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 24h;
    keepalive_timeout 300s;

    location / {
        proxy_pass http://127.0.0.1;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Ssl-Offloaded "1";
        proxy_set_header X-Forwarded-Proto https;
        proxy_set_header X-Forwarded-Port 443;
        #proxy_hide_header X-Varnish;
        #proxy_hide_header Via;
        proxy_set_header X-Forwarded-Proto $scheme;

}

}

And finally the listener on port 8080:

server {
  server_name magento-test.example.com;
  listen 8080;
  set $MAGE_ROOT /var/www/magento-test.example.com;
  set $MAGE_MODE production; # or developer


  include /var/www/magento-test.example.com/nginx.conf.sample;
}

My varnish is configured the following way:

DAEMON_OPTS=" -a :6081 \
               -T localhost:6082 \
               -f /etc/varnish/default.vcl \
               -S /etc/varnish/secret \
               -p feature=+esi_ignore_other_elements \
               -p cli_buffer=16384 \
               -p vcc_allow_inline_c=on \
               -s malloc,256m"

And

backend default {
    .host = "127.0.0.1";
    .port = "8080";
    .first_byte_timeout = 300s;
}

Now i get a 502 error and in the logs I can see the following error:

*35 connect() failed (111: Connection refused) while connecting to upstream, client: xx.xx.xx.xx

If I put the IP in a browser that directs me to a Linksys page (which is what my home router is…)

I tried to remove 127.0.0.1 localhost in the hosts file but still get the same result.

Any idea ?

Best Answer

you need to use varnish port 6081 to proxy https

location / {
        proxy_pass http://127.0.0.1:6081;

user -> nginx:80 -> nginx:443 -> varnish:6081 -> nginx:8080

Related Topic