使用 Varnish 4.1 将 HTTP 重定向到 HTTPS

使用 Varnish 4.1 将 HTTP 重定向到 HTTPS

我一直在尝试使用 Varnish 4.1、Nginx、PHP7.0.15 配置将 www HTTP 重定向到非 www HTTPS,但没有成功。非常感谢您对这个问题的见解:

目的:重定向http://example.com to https://example.com

Nginx 配置:

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;
}

我使用的 Varnish VCL 部分:

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);
    }

}

然而,它根本不起作用。http://example.com doesn't redirect to https://example.com

有人能指出这个问题吗?

谢谢你!

答案1

以下作品:

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);
    }
}

并确保您已将更改应用于默认服务。根据官方手册,最好通过创建一个新文件来完成:Varnish 将 Varnish 放在 80 端口上

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

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

相关内容