LoginSignup
13
20

More than 5 years have passed since last update.

NGINXで接続元IPアドレス(X-Forwarded-For)を設定する

Posted at

NGINX(Proxy)で接続元IP(X-Forwarded-For)を設定します。
オンプロミスで本番環境はBIG-IPが存在して、検証にはない場合など使えるかもしれません。
検証はdocker-composeで実施します。

設定

http, server, locationディレクティブにproxy_set_headerで追加するだけです。

nginx.conf
    location / {
        proxy_set_header X-Forwarded-for $remote_addr; <-----------追加
        proxy_pass   http://web;
    }

$http_x_forwarded_forlog_formatにデフォルトで存在するため、上記のみでwebサーバ側のログに出力されるはずです。
$http_x_forwarded_forが存在しない場合は、下記の様にlog_formatを修正してください。

nginx.conf
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

参考ソースコード

 検証

  • コンテナ起動
bash
$ git clone https://github.com/Thirosue/docker-sample.git
$ cd docker-sample/nginx_x_forwarded_forpwd/
$ docker-compose up -d
Creating proxy ... done
Creating proxy ...
$ docker ps
CONTAINER ID        IMAGE                 COMMAND                  CREATED                  STATUS              PORTS                  NAMES
782e7e485bba        nginx:1.13.1-alpine   "nginx -g 'daemon of…"   Less than a second ago   Up 2 seconds        80/tcp                 web
5e8a5f7c6e59        proxy                 "nginx -g 'daemon of…"   Less than a second ago   Up 2 seconds        0.0.0.0:8080->80/tcp   proxy
  • アクセス

ローカルPCからブラウザで以下に接続

  • 確認

proxyサーバの$remote_addrがwebサーバの$http_x_forwarded_forに設定されていることが確認できる

bash
################ proxyサーバの$remote_addrが
$ docker logs proxy
172.20.0.1 - - [16/Jan/2018:06:52:03 +0000] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36" "-"
################ webサーバの$http_x_forwarded_forに設定されていることが確認できる
$ docker logs web
172.20.0.3 - - [16/Jan/2018:06:52:03 +0000] "GET / HTTP/1.0" 304 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36" "172.20.0.1"
13
20
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
13
20