LoginSignup
10
8

More than 5 years have passed since last update.

NodeJS expressをリバースプロキシさせた時にreq.protocolを取れない罠

Posted at

構成

EC2にnginxを入れてlocalhostで動かしている。サイト自体はSSLに対応しており、httpsアクセスできる

状況

nginx.confでヘッダを付加するようにしているにも関わらず、req.protocolの取得値がhttp。

nginx.conf
        location / {
            proxy_pass http://localhost:3000/;
            proxy_set_header Host                   $host;
            proxy_set_header X-Real-IP              $remote_addr;
            proxy_set_header X-Forwarded-Proto      https;
            proxy_set_header X-Forwarded-Host       $host;
            proxy_set_header X-Forwarded-Server     $host;
            proxy_set_header X-Forwarded-For        $proxy_add_x_forwarded_for;
        }

罠の正体

app.set('trust proxy', 'loopback')をapp.jsに書いてなかった

The request protocol string, “http” or “https” when requested with TLS. When the “trust proxy” setting trusts the socket address, the value of the “X-Forwarded-Proto” header (“http” or “https”) field will be trusted and used if present.

expressの公式ドキュメントに書いてあるんですが見逃してました。公式ドキュメント読もう!

10
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
8