varnish4 常時SSLの書き方


ELB,ロードバランサ,独自プロキシなどリバースプロキシ配下のvarnishで常時SSL対応する方法を書いておく。何となくリバースプロキシを通すとX-Forwarded-Forヘッダが付くようなイメージがあったのだけど実はRFC-7239 Section-5.4に書いてある。

RFC-7239 Section-5.4

The "proto" parameter has the value of the used protocol type. The
syntax of a "proto" value, after potential quoted-string unescaping,
MUST conform to the URI scheme name as defined in Section 3.1 in
[RFC3986] and registered with IANA according to [RFC4395]. Typical
values are "http" or "https".

For example, in an environment where a reverse proxy is also used as
a crypto offloader, this allows the origin server to rewrite URLs in
a document to match the type of connection as the user agent
requested, even though all connections to the origin server are
unencrypted HTTP.



  • vcl_recv で X-Forwarded-Proto が https でなかったら https でリダイレクトさせる。
  • varnishは結果的に80番で受けたURLのみキャッシュする。
  • varnishはX-Forwarded-Protoを消さず下流に流す。
  • nginx は常に80番を受ける。X-Forwarded-Protoを見てリクエストがhttpかhttpsか判断する。


sub vcl_recv {
if (req.http.X-Forwarded-Proto != "https)
return (synth(750, ""));
return (hash);

sub vcl_synth {
if (req.http.X-Forwarded-Proto != "https")
if (req.status = 750) {
set resp.status = 301;
set resp.http.Location = "https://" + + req.url;


Copyright© , 2018 AllRights Reserved Powered by AFFINGER4.