如何在 Debian 或 Ubuntu 上将 Nginx 用作全局流量指挥器

介绍

随着客户群的增长,服务器(服务器)和客户之间的距离也一样。我们都知道,如果服务器的负载增加,你会扩展,但是当 distance 是一个问题时,该怎么办?

解决方案很简单:将服务器(服务器)安装在更接近您的客户群的地理位置,并根据其位置将其导向。

在本指南中,我们将配置 Nginx 来检测和重定向客户到指向更相应的地理服务器的子域。

前提条件

要完成本指南,您需要一个具有sudo特权的用户。 您还需要知道如何在不同地区创建服务器。

假设

本文为易读性提出了一些假设。

  • 您的域名是 www.example.com
  • 您的主要服务器位于美国
  • 您想为欧洲和亚洲安装 GTD
  • 您的服务器 IP 如下: US: 1.1.1.1 EU: 1.1.1.2 AS: 1.1.3

子域和 DNS 配置

对于本教程,让我们使用eu.example.com为欧洲和as.example.com为亚洲。

对于每一个子域,在您的 DNS 配置中添加一个A 记录,用该区域的服务器的 IP:

  • eu.example.com - 1.1.1.2
  • as.example.com - 1.1.1.3

它应该看起来像这样的东西:

dns

安装 Nginx 和 GeoIP

要使用 GeoIP 模块使用 Nginx,您有两种选择: 1)使用预编译的包(只有 -full 和 -extra 有 GeoIP 模块)或 2)用 --with-http_geoip_module 配置参数编译您的 nginx – 在这种情况下,您还需要 geoip-dev 库。

让我们使用现有的存储库包。

1sudo apt-get update
2sudo apt-get install nginx-full geoip-database

现在既有 Nginx 又有 GeoIP 二进制,但还有一件事:GeoIP 的城市数据库包含区域信息,您需要手动下载并安装。

1wget -N http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
2gunzip GeoLiteCity.dat.gz
3mv GeoLiteCity.dat /usr/share/GeoIP/

配置 Nginx 和您的虚拟主机

在这里,我们将告诉 Nginx GeoIP 数据库文件的位置,并在我们的虚拟主机中,我们将根据其地理信息来配置 Nginx 如何响应请求。

打开nginx.conf(默认为/etc/nginx/nginx.conf) 使用您喜爱的编辑器。 添加geoip_city /usr/share/GeoIP/GeoLiteCity.dat字段。 您的nginx.conf将看起来像这样:

1http {
2  geoip_city /usr/share/GeoIP/GeoLiteCity.dat;
3  ...
4}

拯救它。

现在让我们编辑您的虚拟主机(默认 /etc/nginx/sites-available/default)。内部我们需要创建一个 map 并将子域添加到 server_name 指令中。

Nginx中的地图允许我们根据$geoip_city_continent_code的值设置变量$closest_server

1map $geoip_city_continent_code $closest_server {
2  default www.example.com;
3  EU eu.example.com;
4  AS as.example.com;
5}

接下来,我们将基于位置的子域添加到$server_name指令中:

1server {
2  server_name example.com
3              www.example.com
4              eu.example.com
5              as.example.com;
6  ...
7}

过程的最后一部分是在虚拟主机中创建一个条件,将访问者重定向到最近的服务器。

1server {
2  ...
3
4  if ($closest_server != $host) {
5    rewrite ^ $scheme://$closest_server$request_uri break;
6  }
7
8  ...
9}

完成所有更改后,您的虚拟主机文件将看起来像这样:

 1map $geoip_city_continent_code $closest_server {
 2  default www.example.com;
 3  EU eu.example.com;
 4  AS as.example.com;
 5}
 6
 7server {
 8  server_name example.com
 9              www.example.com
10              eu.example.com
11              as.example.com;
12
13  if ($closest_server != $host) {
14    rewrite ^ $scheme://$closest_server$request_uri break;
15  }
16
17  ...
18}

** 重复此步骤为您想要配置的每个服务器,这样所有的服务器都将作为流量管理器。

运行几个测试

完成所有这些步骤后,最后一个步骤是测试你已经做过的事情. 使用 Nginx 时,在应用前始终测试新配置。

_Nginx 提供了测试其配置文件的选项,而不会影响当前运行的 Nginx。

「nginx -t」、「服务 nginx configtest」或「/etc/init.d/nginx configtest」

如果一切顺利 - 重新加载您的 Nginx 配置:

「nginx -s 重新加载」、「服务 nginx 重新加载」或「/etc/init.d/nginx 重新加载」

打开浏览器并访问www.example.com:

如果您在欧洲使用代理服务访问该网站,您应该被重定向到‘eu.example.com’:

如果您使用亚洲的代理访问该网站,您应该被重定向到as.example.com:

从现在开始,您的全球访客将被立即重定向到他们最近的服务器,从而改善他们在您的网站上的体验。

Submitted by: Alex Soban
Published At
Categories with 技术
comments powered by Disqus