Redirect HTTP to HTTPS using Varnish 4.1

Loading...

Redirect HTTP to HTTPS using Varnish 4.1

I have been trying to config the redirection of www HTTP to non-www HTTPS with Varnish 4.1, Nginx, PHP7.0.15, but it's not successful. Really appreciate your insight on the issue:
The purpose: to redirect http://example.com to https://example.com
Nginx conf:
server {
   listen  443 ssl http2;
   listen  [::]:443 ssl http2;
   server_name example.com;
   port_in_redirect off;

   ssl on;
   include snippets/ssl-example.com.conf;
   include snippets/ssl-params.conf;

   location / {
     proxy_pass http://127.0.0.1:80; 
     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 X-Forwarded-Proto https;
     proxy_set_header HTTPS "on";
   }
}


server {
  listen 8080;
  listen [::]:8080;
  server_name  example.com;
  root /var/www/html/example.com;
  index index.php;
  port_in_redirect off;

  location / {
        try_files $uri $uri/ /index.php?$args;
  }

  location ~ \.php$ {
       try_files $uri =404;
       fastcgi_split_path_info ^(.+\.php)(/.+)$;
       include fastcgi_params;
       fastcgi_index index.php;
       fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
       fastcgi_param HTTPS on;
       fastcgi_pass unix:/var/run/php/php7.0-fpm.sock;
   }
}

server {
  listen  8080;
  listen  [::]:8080;
  server_name  www.example.com;
  return  301 https://example.com$request_uri;
}

And the Varnish VCL section, which I use:
sub vcl_recv {
    if ( (req.http.host ~ "^(?i)www.example.com" || req.http.host ~ "^(?i)example.com") && req.http.X-Forwarded-Proto !~ "(?i)https") {
       return (synth(750, ""));
    }
}

sub vcl_synth {
    if (resp.status == 750) {
        set resp.status = 301;
        set resp.http.Location = "https://example.com" + req.url;
        return(deliver);
    }

}

However, it just doesn't work. http://example.com doesn't redirect to https://example.com
Can anyone point out the issue? 
Thank you!

Solutions/Answers:

Answer 1:

The below works:

sub vcl_recv {
    if (client.ip != "127.0.0.1" && req.http.host ~ "example.com") {
       set req.http.x-redir = "https://example.com" + req.url;
       return(synth(850, ""));
    }
}

sub vcl_synth {
    if (resp.status == 850) {
       set resp.http.Location = req.http.x-redir;
       set resp.status = 301;
       return (deliver);
    }
}

And make sure you have applied changes to the default service. According the official manual, it is best done by creating a new file:Varnish Put Varnish on port 80

/etc/systemd/system/varnish.service.d/customexec.conf:

[Service]
ExecStart=
ExecStart=/usr/sbin/varnishd -a :80 -T localhost:6082 -f /etc/varnish/default.vcl -S /etc/varnish/secret -s malloc,256m

References

Loading...