如何在生产环境中运行的 Nginx 上安装 Geoip2 模块?

Posted

技术标签:

【中文标题】如何在生产环境中运行的 Nginx 上安装 Geoip2 模块?【英文标题】:How install the Geoip2 module on a Nginx running in a production environment? 【发布时间】:2020-06-05 11:04:35 【问题描述】:

有人可以向我解释如何在生产环境中运行的 nginx 1.14 上安装 Geoip2 模块而不破坏当前配置吗?

我只找到说明如何在第一次安装期间使用 geoip2 模块编译 Nginx 的源代码。

我使用的是 Linux 发行版 Debian 10。

谢谢

【问题讨论】:

【参考方案1】:

首先安装 libmaxminddb 库:

sudo add-apt-repository ppa:maxmind/ppa
sudo apt update
sudo apt install libmaxminddb0 libmaxminddb-dev mmdb-bin

下载并解压geoip2模块:

https://github.com/leev/ngx_http_geoip2_module/archive/3.3.tar.gz
tar zxvf 3.3.tar.gz

下载nginx源码:

wget https://nginx.org/download/nginx-1.14.2.tar.gz
tar zxvf nginx-1.14.2.tar.gz
cd nginx-1.14.2

然后将 geoip2 构建为动态模块:

./configure --with-compat --add-dynamic-module=/path/to/ngx_http_geoip2_module
make
make modules

这将产生objs/ngx_http_geoip2_module.so。如果您愿意,可以手动将其复制到您的 nginx 模块路径。

例如:

cp objs/ngx_http_geoip2_module.so /etc/nginx/modules

获取最新数据库(需要免费注册):

https://dev.maxmind.com/geoip/geoip2/geolite2/#Download_Access

Unpack dtabase files to /usr/share/GeoIP2 directory

将以下行添加到您的 nginx.conf:

load_module modules/ngx_http_geoip2_module.so;

添加到 nginx.conf http 部分:

geoip2 /usr/share/GeoIP2/GeoLite2-Country.mmdb 
    auto_reload 60m;
    $geoip2_metadata_country_build metadata build_epoch;
    $geoip2_data_country_code default=US source=$variable_with_ip country iso_code;
    $geoip2_data_country_name country names en;

geoip2 /usr/share/GeoIP2/GeoLite2-City.mmdb 
    auto_reload 60m;
    $geoip2_metadata_city_build metadata build_epoch;
    $geoip2_data_city_name default=London city names en;

然后重启 Nginx 服务。希望对您有所帮助。

【讨论】:

以上是关于如何在生产环境中运行的 Nginx 上安装 Geoip2 模块?的主要内容,如果未能解决你的问题,请参考以下文章

nginx+uwsgi+virtualenv+django搭建django生产运行环境

Django 生产环境部署-记录 nginx+uwsgi+Django

面向生产和开发环境的LNP基础镜像

在生产环境中运行 NodeJS 服务器

一次生产上由于Nginx引起的HTTP请求Header参数丢失的问题

linux在非root权限无外网(只有内网的生产环境)情况下安装nginx+mysql+php