如何使用 GeoIP 模块安装 Nginx

在本教程中,我们将向您展示如何在 CentOS 上安装带有 GeoIP 模块的 Nginx。 对于那些不知道的人, Nginx GeoIP 国家和城市地理定位模块只需几个简单的步骤即可安装。 它为您带来了一个地理定位层,允许您显示网站的某些部分,甚至根据最终用户的地理位置分割流量。 默认情况下,当你从 yum 安装模块时,Nginx 不会附带 GeoIP 模块(这是模块:HttpGeoipModule),所以我们将从源安装和活动模块。

本文假设您至少具备 Linux 的基本知识,知道如何使用 shell,最重要的是,您将网站托管在自己的 VPS 上。 安装非常简单,假设您在 root 帐户下运行,如果不是,您可能需要添加 ‘sudo‘ 到命令以获取 root 权限。 我将向您展示如何在 CentOS 系统上逐步安装 Nginx With GeoIP Module。

使用 GeoIP 模块安装 Nginx

第 1 步。首先,让我们首先确保您的系统是最新的。

sudo yum install epel-release sudo yum update

步骤 2. 安装所有需要依赖项。

现在安装需要一个用于编译的包:

yum install gcc-c++ pre pcre-devel zlib zlib-devel -y

步骤 3. 下载并安装 Nginx。

现在我们从这里下载最新的稳定版 Nginx 这里 并使用 GeoIP 模块支持构建它。

cd /opt/nginx/ wget https://nginx.org/download/nginx-1.21.5.tar.gz tar -zxf nginx-1.21.5.tar.gz cd nginx-1.21.5/ ./configure --prefix=/etc/nginx  --sbin-path=/etc/nginx/sbin/nginx  --conf-path=/etc/nginx/conf/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/ninx.lock  --user=nobody  --with-http_geoip_module  --with-http_gzip_static_module  --with-http_secure_link_module  --without-mail_pop3_module  --without-mail_imap_module  --without-mail_smtp_module  --without-http_ssi_module

完成编译后,接下来使用以下命令安装 Nginx:

make make install

步骤 4. 为 Nginx 创建一个初始化脚本。

首先,将用户 Nginx 添加到系统中。 这是一次性命令:

useradd -r nginx

我们需要设置文件 /etc/init.d/nginx 在系统启动时运行:

wget -O /etc/init.d/nginx https://gist.github.com/sairam/5892520/raw/b8195a71e944d46271c8a49f2717f70bcd04bf1a/etc-init.d-nginx chmod 0755 /etc/init.d/nginx chown root:root /etc/init.d/nginx

最后,启动 Nginx:

systemctl restart nginx

步骤 5. 在 CentOS 系统上安装 GeoIP 库。

现在运行以下命令来安装 GeoIP 库

sudo yum install geoip geoip-devel

安装成功后,库会存放在 /usr/share/GeoIP/GeoIP.dat 可下载最新更新 这里.

步骤 5. 配置 Nginx

接下来,我们配置主文件:

nano /etc/nginx/conf/nginx.conf

添加以下文件:

http { [...] geoip_country /usr/share/GeoIP/GeoIP.dat; map $geoip_country_code $allowed_country { default yes; CN no; } [...] }

之后,我们配置 Nginx 虚拟主机:

nano /etc/nginx/conf.d/yourdomain.conf

添加以下行:

server { [...] if ($allowed_country = no) { return 444; # # This means the server will stop processing, returns error 444 (The connection was reset), # # And ignore always sending the response header. # # Replace 444 by 403 if you want } [...] }

上述配置将接受所有 IP 并仅禁止来自中国 IP (CN) 的 IP。 关于GeoIP数据库中国家的代码,可以参考 这里.

恭喜! 您已经成功安装了带有 GeoIP 模块的 Nginx。 感谢您使用本教程在 Linux 系统上安装带有 GeoIP 模块的 Nginx。 如需更多帮助或有用信息,我们建议您查看 Nginx 官方网站.