Configure Varnish to auto direct from http to https

In SSH terminal, edit the domain configuration file in /etc/nginx/conf.d/

  1. Configure Nginx as SSL Proxy
server {
        listen 443 ssl http2;
        server_name pquan.info;  #change mine to your domain.

        # SSL #You can use Let's Encrypt or Comodo
        ssl_certificate /etc/nginx/ssl/nginx.crt;
        ssl_certificate_key /etc/nginx/ssl/nginx.key;

        location / {
            proxy_pass http://127.0.0.1:8080;
            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 https;
            proxy_set_header X-Forwarded-Port 443;
            proxy_set_header Host $host;
        }
}
  1. Configure Varnish to auto direct http to https

In SSH terminal, type nano /etc/varnish/default.vcl and add the following code:

sub vcl_recv {
        # Ask Varnish to fire 750 status for HTTP requests from external IPs and port 80,
        # and not from SSL Termination Proxy (Nginx).
        if ( (req.http.host ~ "^(?i)www. pquan.info " || req.http.host ~ "^(?i)pquan.info") && req.http.X-Forwarded-Proto !~ "(?i)https") {
                return (synth(750, ""));
        }
}

sub vcl_synth {
        # Listen to 750 status from vcl_recv.
        if (resp.status == 750) {
                set resp.status = 301;
                set resp.http.Location = "https://pquan.info " + req.url;
                return(deliver);
        }
}

then, type command service varnish reload to reload Varnish configuration.

If it still does not convert http to https, more specifically, if you type only yourdomain.com in the broswer, it’ll say refused to connect, that means you are still only able to visit https:// yourdomain.com. So you need to look in the file /etc/varnish/varnish.param and change the following value:

VARNISH_LISTEN_PORT=80

Comment

Your email address will not be published. Required fields are marked *