Образовательный проект «SnakeProject» Михаила Козлова

Навигация

⇒ FreeBSD and Nix ⇐

CISCO

Voice(Asterisk\Cisco)

Microsoft

Powershell

Python

SQL\T-SQL

Общая

WEB Разработка

ORACLE SQL \ JAVA

Мото

Стрельба, пневматика, оружие

Саморазвитие и психология


Установка libnginx-mod-http-geoip2 в Ubuntu 22.04


Установка libnginx-mod-http-geoip2 в Ubuntu 22.04

Закрываем доступ к web ресурсам по геолокации
Настройки с помощью модуля ngx_http_geoip2_module и базы GeoIP2

Варианты установки

# sudo apt-get update
# sudo apt-get -y install libnginx-mod-http-geoip2 geoipupdate

# sudo apt update
# sudo apt -y install libnginx-mod-http-geoip2 geoipupdate

# sudo aptitude update
# sudo aptitude -y install libnginx-mod-http-geoip2 geoipupdate

Проверка Nginx на GeoIP модуль:
# nginx -V

Ищем значение - with-http_geoip_module, если нет - пересобираем

Проверяем:
# cat /etc/nginx/modules-enabled/50-mod-http-geoip2.conf
load_module modules/ngx_http_geoip2_module.so;

Пример сборки с нуля:
# wget https://nginx.org/download/nginx-1.19.6.tar.gz && tar xvf nginx-1.19.6.tar.gz
# cd /tmp && git clone https://github.com/leev/ngx_http_geoip2_module
# ./configure
--prefix=/etc/nginx
--sbin-path=/usr/sbin/nginx
--modules-path=/usr/lib64/nginx/modules
--conf-path=/etc/nginx/nginx.conf
--error-log-path=/var/log/nginx/error.log
--http-log-path=/var/log/nginx/access.log
--pid-path=/var/run/nginx.pid
--lock-path=/var/run/nginx.lock
--http-client-body-temp-path=/var/cache/nginx/client_temp
--http-proxy-temp-path=/var/cache/nginx/proxy_temp
--http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp
--http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp
--http-scgi-temp-path=/var/cache/nginx/scgi_temp
--user=nginx --group=nginx --with-compat
--with-file-aio --with-threads --with-http_addition_module
--with-http_auth_request_module --with-http_dav_module
--with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module
--with-http_mp4_module --with-http_random_index_module --with-http_realip_module
--with-http_secure_link_module --with-http_slice_module --with-http_ssl_module
--with-http_stub_status_module --with-http_sub_module --with-http_v2_module
--with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module
--with-stream_ssl_module --with-stream_ssl_preread_module
--with-cc-opt='-O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 \
-Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches \
-specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 \
-m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -fPIC'
--with-ld-opt='-Wl,-z,relro -Wl,-z,now -pie'
--add-module=/tmp/ngx_http_geoip2_module

Пример только с динамическим модулем:
# ./configure --add-dynamic-module=/tmp/ngx_http_geoip2_module
# make modules

Пример добавления модуля уже работающему nginx:
# ./configure --add-module=/tmp/ngx_http_geoip2_module $(nginx -V)

Скопируйте из objs ngx_http_geoip2_module.so в папку:
/etc/nginx/modules

Подключить в конфигурационном файле:
load_module modules/ngx_http_geoip2_module.so;

Пересоберите:
# make && make install

В установленном nginx найдете:
/usr/lib/nginx/modules/ngx_http_geoip2_module.so

Открываем брандмауэр:
# firewall-cmd --permanent --add-service=http
# firewall-cmd --permanent --add-service=https
# firewall-cmd --reload

Группа и учетка:
# groupadd -g 991 nginx
# useradd -g 991 -u 991 -c "Nginx server" -d /var/lib/nginx -s /sbin/nologin nginx
# mkdir -p /var/cache/nginx/client_temp

Описываем юнит:
/etc/systemd/system/nginx.service:
[Unit]
Description=The NGINX proxy server
After=syslog.target network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target
[Service]
Type=forking
PIDFile=/var/run/nginx.pid
ExecStartPre=/usr/sbin/nginx -t
ExecStart=/usr/sbin/nginx
ExecReload=/usr/sbin/nginx -s reload
ExecStop=/bin/kill -s QUIT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target

Автозагрузка:
# systemctl daemon-reload
# systemctl enable nginx
# systemctl start nginx

Зарегистрируйтесь на сайте MaxMind и скачайте базы стран и городов:
# wget "https://download.maxmind.com/app/geoip_download_by_token?edition_id=GeoLite2-Country&date=20201222&suffix=tar.gz&token=v2.local.XXXXXXXXXX" -O country.tar.gz
# wget "https://download.maxmind.com/app/geoip_download_by_token?edition_id=GeoLite2-City&date=20201222&suffix=tar.gz&token=v2.local.XXXXXXXXXX" -O city.tar.gz

Распакуем и переместим в папку /etc/nginx/geo:
# mkdir -p /etc/nginx/geo
# tar xvf city.tar.gz --dir /etc/nginx/geo/
# tar xvf country.tar.gz --dir /etc/nginx/geo/
# cd /etc/nginx/geo/
# mv GeoLite2-City_20201222/GeoLite2-City.mmdb GeoLite2-City.mmdb
# mv GeoLite2-Country_20201222/GeoLite2-Country.mmdb GeoLite2-Country.mmdb

Конфигурация

В файл конфигурации nginx.conf добавляем следующие строки в блок http
После “default no” доступ разрешим “RU yes”, у кого GEO Location установлен, как RU (Russia / Россия)

geoip2 /etc/nginx/geo/GeoLite2-Country.mmdb {
    $geoip2_data_city_name city names en;
}
geoip2 /etc/nginx/geo/GeoLite2-City.mmdb {
    $geoip2_data_country_iso_code country iso_code;
}
map $geoip2_data_country_iso_code $allowed_country {
    default no;
    RU allow;
}

В блоке server опишем код возврата блоков:
if ($allowed_country = no) {
    return 403;
}

Перечитываем конфу:
# nginx -t
# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful
# nginx -s reload

Автоматическое обновление баз MaxMind

В /etc/GeoIP.conf укажем параметры из личного кабинета - AccountID и LicenseKey
Ключ можно сгенерировать в личном кабинете

$ cd /etc/cron.d
$ sudo touch geoipupdate
0 0 * * * /usr/bin/geoipupdate

Еще пример

Файл GeoLite2-Country.mmdb можно попробовать на шару взять отсюда:
https://git.io/GeoLite2-Country.mmdb
https://github.com/P3TERX/GeoLite.mmdb/raw/download/GeoLite2-Country.mmdb

/etc/nginx/nginx.conf:
http {
    geoip2 /var/lib/GeoIP/GeoLite2-Country.mmdb {
       $geoip2_data_country_iso_code country iso_code;
    }

    map $geoip2_data_country_iso_code $allowed_country {
       default no;
       RU yes; # Russia
       DE yes; # Germany
    }

    server {
       # Block forbidden country
       if ($allowed_country = no) {
           return 444;
       }

       [...]
    }
}

Поддержать автора рублем: https://yoomoney.ru/to/410012210709233

 


Комментарии пользователей

Эту новость ещё не комментировалиНаписать комментарий
Анонимам нельзя оставоять комментарии, зарегистрируйтесь!

Контакты Группа ВК Сборник материалов по Cisco, Asterisk, Windows Server, Python и Django, SQL и T-SQL, FreeBSD и LinuxКод обмена баннерами Видео к IT статьям на YoutubeВидео на другие темы Смотреть
Мои друзья: Советы, помощь, инструменты для сис.админа, статическая и динамическая маршрутизация, FreeBSD

© Snakeproject.ru создан в 2013 году.
При копировании материала с сайта - оставьте ссылку.

Рейтинг@Mail.ru
Рейтинг@Mail.ru Яндекс.Метрика





Поддержать автора и проект