7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Tornado + nginx の時のIPの取得方法

Posted at

TornadoでクライアントIPアドレスを取得するとき、

#!/usr/bin/python
# -*- coding: utf-8 -*-

from tornado import web,ioloop

class IndexHandler(web.RequestHandler):
    def get(self):
        ip = self.request.remote_ip
        self.write(ip)

handlers = [
    (r'/', IndexHandler),
]

settings = dict(
    debug = True,
)

app = web.Application(handlers, **settings)
app.listen(8000)
ioloop.IOLoop.instance().start()

で取得できます。

ただしnginxで

http {
    upstream example.server.com {
        server 127.0.0.1:8000;
    }
    server {
        listen 80;
        server_name example.server.com;
        location / {
            proxy_pass_header Server;
            proxy_set_header Host $http_host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Scheme $scheme;
            proxy_pass example.server.com;
            proxy_next_upstream error;
        }
    }
}

のような設定をしてtornadoを動かしていると全てIPが127.0.0.1になってしまいます。

なのでtornadoのIndexHandlerを

class IndexHandler(web.RequestHandler):
    def get(self):
        ip = self.request.headers['X-Real-IP']
        self.write(ip)

としてあげれば、無事取得出来ました。

nginxがロードバランサ的な動きをしているので、考えてみれば当たり前なんですが、最初気付かず少しハマってしまいました。。。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?