LoginSignup
6
4

More than 5 years have passed since last update.

Nginx + ASP.NET CoreでクライアントのIPアドレスを取得する

Last updated at Posted at 2017-04-21

ASP.NET CoreでWebアプリを作りました。
Linuxサーバ(Debian 8.6)にNginxを入れて、リバースプロキシの設定を行い、デプロイして、動きました。
でも、クライアントのIPアドレス(REMOTE_ADDR)が127.0.0.1になっています・・・
そんなときの解決法。

  • .NETCoreApp 1.1
  • Debian 8.6
  • Nginx 1.6.2

アプリ側の設定

Configureに追記

公式ドキュメントの通り、Startup.cs の Configure メソッド内に下記を追記します。
app.UseMvcの記述よりも先に書きます。

Startup.cs
// クライアントのIPアドレスを取得するため、NginxのProxyヘッダを使う設定
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});

クライアントIPアドレスの表示

HttpContextの、Connectionプロパティから取得できます。
テストのため、アクションメソッドでViewDataにセットして、Viewに表示します。

public class HomeController : Controller
{
    public IActionResult Index()
    {
        ViewData["RemoteAddress"] = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();

        return View();
    }
}

Nginxの設定

HttpRealModule設定ファイルの作成

バックエンド側のサーバ(Kestrel)で、X-Forwarded-For の値をクライアントのIPアドレスとして使用するようするため、HttpRealModuleを使います。

# vi /etc/nginx/conf.d/realip.conf
/etc/nginx/conf.d/realip.conf
set_real_ip_from   127.0.0.1;
set_real_ip_from   ::1;
real_ip_header     X-Forwarded-For;
real_ip_recursive  on;

このファイルは、/etc/nginx/nginx.conf から自動的に読み込まれます。

サイトファイルの編集

ASP.NETサイト用にファイル(dotnetapp)を作ります。
Debian の Nginxパッケージには、proxy_paramsファイルが既に用意されているので、それをincludeします。

/etc/nginx/sites-available/dotnetapp
server {
        listen 80;
        location / {
                proxy_pass http://localhost:5000;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection keep-alive;
                proxy_cache_bypass $http_upgrade;

                include /etc/nginx/proxy_params;     # 追記します
        }
}

"proxy_xxx"の設定は、公式ドキュメントの通りに記述しています。
ちなみに、/etc/nginx/proxy_params ファイルの内容は、下記のようになっていました。

/etc/nginx/proxy_params
proxy_set_header 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 $scheme;

作成したサイトを有効にします。

# rm /etc/nginx/sites-enabled/default
# ln -s /etc/nginx/sites-available/dotnetapp /etc/nginx/sites-enabled/

# systemctl restart nginx.service

これでめでたく、クライアントのIPアドレスがアプリから取得できるようになりました。

参考ページ

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