# 从 NGINX 迁移到 APISIX

用户从 NGINX 迁移到 APISIX 是因为它的易用性和可扩展性。例如，APISIX：

1. 支持配置热加载，无需停机。
2. 开箱即用地支持 [灰度发布](https://docs.apiseven.com/apisix/production/upgrade/canary-deployment.md)、[认证](https://docs.apiseven.com/apisix/how-to-guide/authentication/set-up-sso-with-keycloak.md) 和 [可观测性](https://docs.apiseven.com/apisix/how-to-guide/observability/monitor-apisix-with-prometheus.md)。
3. 可以通过 [Admin API](https://docs.apiseven.com/apisix/reference/admin-api.md) 或 [YAML 配置文件](https://docs.apiseven.com/apisix/reference/file-standalone-configurations.md) 进行配置。
4. 提供可扩展性，允许用户 [使用 Lua](https://docs.apiseven.com/apisix/how-to-guide/custom-plugins/create-plugin-in-lua.md) 和其他编程语言开发自定义插件。

本指南将引导你完成将典型场景的 NGINX 配置迁移到等效 APISIX 配置的过程。

警告

在部署到生产环境之前，请确保已在沙箱环境中测试迁移后的配置。

## 配置反向代理[​](#配置反向代理 "配置反向代理的直接链接")

充当代理并将请求转发到上游服务器是 NGINX 和 APISIX 的主要功能。

此示例使用 NGINX 和 APISIX 将对 `/anything/` 路径的请求转发到上游 `httpbin.org`。

要在 NGINX 中代理请求，使用 `proxy_pass` 指令：

/etc/nginx/nginx.conf

```
http {

    server {

        listen 80;

        location /anything/ {

            proxy_pass http://httpbin.org:80;

        }

    }

}
```

❶ 在端口 80 上监听请求。

❷ 匹配以 `/anything/` 开头的位置。

❸ 将匹配的请求代理到 `httpbin.org`。

APISIX 通过 [路由](https://docs.apiseven.com/apisix/key-concepts/routes.md) 实现相同的配置。

创建一个路由，如下所示：

```
curl -i "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" -d '

{

  "id": "apisix-anything",

  "uri": "/anything/*",

  "upstream": {

    "type": "roundrobin",

    "nodes": {

      "httpbin.org:80": 1

    }

  }

}'
```

❶ 匹配所有路径前缀为 `/anything/` 的请求。

❷ 将匹配的请求代理到 `httpbin.org`。

向创建的路由发送请求：

```
curl -i "http://127.0.0.1:9080/anything/nothing"
```

你应该看到带有以下内容的 `HTTP/1.1 200 OK` 响应：

```
{

  "args": {},

  "data": "",

  "files": {},

  "form": {},

  "headers": {

    "Accept": "*/*",

    "Host": "127.0.0.1",

    "User-Agent": "curl/8.4.0",

    "X-Amzn-Trace-Id": "Root=1-661fc252-35c621bc2d2b961c6ce98366",

    "X-Forwarded-Host": "127.0.0.1"

  },

  "json": null,

  "method": "GET",

  "origin": "192.0.2.1, 45.253.168.124",

  "url": "http://127.0.0.1/anything/nothing"

}
```

有关更复杂的路由场景，请参阅 [流量管理指南](https://docs.apiseven.com/apisix/how-to-guide/traffic-management/rate-limiting.md)。

## 配置负载均衡[​](#配置负载均衡 "配置负载均衡的直接链接")

NGINX 也广泛用作负载均衡器，在多个上游服务器之间分发传入请求。

此示例使用 NGINX 和 APISIX 在两个上游 `httpbin.org` 和 `mock.api7.ai` 之间平衡负载，同时保留一个故障转移服务器 `192.0.0.1` 用于故障情况。

这些上游在 NGINX 配置中的 `upstream` 块（上下文）中指定：

/etc/nginx/nginx.conf

```
http {

    upstream backend {

        server httpbin.org:443 weight=3;

        server mock.api7.ai:443 weight=1;

        server 192.0.0.1:443 backup;

    }



    server {

        listen 80;

        location / {

            proxy_pass https://backend;

        }

    }

}
```

❶ 创建一个名为 `backend` 的上游。

❷ 配置上游节点 `httpbin.org` 和 `mock.api7.ai`，权重分别为 3 和 1。

❸ 配置故障转移服务器 `192.0.0.1`，以便在上述节点发生故障时回退。

APISIX 通过 [上游](https://docs.apiseven.com/apisix/key-concepts/upstreams.md) 配置中的 [`nodes`](https://docs.apiseven.com/apisix/reference/admin-api.md#tag/Upstreams/paths/~1apisix~1admin~1upstreams/post) 属性实现相同的配置。

创建一个具有多个上游节点的路由：

```
curl -i "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" -d '

{

  "id": "apisix-headers",

  "uri": "/headers",

  "upstream" : {

    "type": "roundrobin",

    "nodes": [

      { "host": "httpbin.org", "port": 443, "weight": 3 },

      { "host": "mock.api7.ai", "port": 443, "weight": 1 },

      { "host": "192.0.0.1", "port": 443, "weight": 1, "priority": -1 }

    ],

    "pass_host": "node",

    "scheme": "https"

  }

}'
```

❶ 使用加权轮询算法进行负载均衡。有关其他选项，请参阅 [负载均衡](https://docs.apiseven.com/apisix/key-concepts/upstreams.md#load-balancing)。

❷ 配置上游节点 `httpbin.org` 和 `mock.api7.ai`，权重比为 3:1。

❸ 配置故障转移服务器 `192.0.0.1`，以便在上述节点发生故障时回退。

向创建的路由发送 50 个请求以验证负载均衡：

```
resp=$(seq 50 | xargs -I{} curl "http://127.0.0.1:9080/headers" -sL) && \

  count_httpbin=$(echo "$resp" | grep "httpbin.org" | wc -l) && \

  count_mockapi7=$(echo "$resp" | grep "mock.api7.ai" | wc -l) && \

  echo httpbin.org: $count_httpbin, mock.api7.ai: $count_mockapi7
```

你应该看到接近所配置 3:1 比例的分布。APISIX 运行多个 worker 时，实际计数可能会有所不同：

```
httpbin.org: 38, mock.api7.ai: 12
```

## 服务静态文件[​](#服务静态文件 "服务静态文件的直接链接")

NGINX 和 APISIX 可以直接服务静态文件。这通常包括 HTML、CSS、JavaScript、图像、字体和其他无需修改即可提供给客户端的媒体文件。

此示例使用 NGINX 和 APISIX 缓存并代理来自 [Web 超文本应用技术工作组 (WHATWG) 公共 GitHub 仓库](https://github.com/whatwg) 的静态文件。

NGINX 支持在 location 块中使用正则表达式来根据文件扩展名匹配文件，如下所示：

/etc/nginx/nginx.conf

```
http {

    proxy_cache_path /data/nginx/cache keys_zone=mycache:10m;

    server {

        listen 80;

        proxy_cache mycache;

        location ~* ^/whatwg/(.+\.(jpeg|html))$ {

            proxy_pass https://raw.githubusercontent.com;

        }

    }

}
```

❶ 将缓存内容存储在 `/data/nginx/cache` 中，并使用 10 MB 的共享内存区域来存储缓存键。

❷ 使用创建的缓存 `mycache`。

❸ 使用正则表达式匹配前缀为 `/whatwg/` 且文件扩展名为 `.jpeg` 或 `.html` 的请求。

❹ 将匹配的请求代理到 `raw.githubusercontent.com`。

APISIX 使用 [变量](https://docs.apiseven.com/apisix/reference/built-in-variables.md) 来匹配路径。然后，为了缓存响应，APISIX 使用 [`proxy-cache`](https://docs.apiseven.com/hub/proxy-cache.md) 插件。

创建一个启用 `proxy-cache` 的路由：

```
curl -i "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" -d '

{

  "id": "apisix-whatwg",

  "uri": "/whatwg/*",

  "vars": [["uri", "~~", "\\.(?:jpeg|html)$"]],

  "plugins": {

    "proxy-cache": {}

  },

  "upstream": {

    "type": "roundrobin",

    "scheme": "https",

    "pass_host": "node",

    "nodes": {

      "raw.githubusercontent.com": 1

    }

  }

}'
```

❶ 使用 `uri` 变量匹配以 `.jpeg` 或 `.html` 结尾的请求。

❷ 启用 `proxy-cache` 以缓存响应。

❸ 将匹配的请求代理到 `raw.githubusercontent.com`。

向创建的路由发送 HTML 文件请求：

```
curl -i "http://127.0.0.1:9080/whatwg/html/main/404.html"
```

你应该收到一个 `HTTP/1.1 200 OK` 响应，并看到以下文件内容：

```
<!DOCTYPE html>

<script src="/link-fixup.js" defer></script>

<title>404 Not Found</title>

<style>

  body.loading div.failed,

  body.failed div.loading,

  div.failed {

    display: none;

  }

  body.loading div.loading,

  body.failed div.failed,

  div.loading {

    display: block;

  }

</style>

<body onload="document.body.className = 'failed'">

  <script>

    document.body.className = "loading";

  </script>

  <div class="loading">

    <p>Loading...</p>

  </div>

  <div class="failed">

    <h1>Not Found</h1>

    <p>The page you are looking for is no longer available at this URL.</p>

    <p>

      Links to the multipage version of the specification are unfortunately

      likely to break over time. You might be able to find what you want from

      <a href="/multipage/">the contents page</a>.

    </p>

    <p>

      If you have found a broken link on the WHATWG site itself, please

      <a href="https://github.com/whatwg/html/issues/new">file an issue</a>. If

      you found a broken link from another site pointing to the WHATWG site,

      please let that site know of the problem instead. Thanks!

    </p>

  </div>

</body>
```

验证不带字面 `.jpeg` 或 `.html` 扩展名的路径不会匹配该路由：

```
curl -i "http://127.0.0.1:9080/whatwg/filexhtml"
```

你应该收到 `HTTP/1.1 404 Not Found` 响应。

## 配置 SSL 终止[​](#配置-ssl-终止 "配置 SSL 终止的直接链接")

NGINX 可以终止来自客户端的 HTTPS 流量，以减轻上游的解密负担。APISIX 也开箱即用地支持此功能。

此示例使用 NGINX 和 APISIX 在通过 HTTP 将请求代理到上游 `httpbin.org` 之前终止 SSL。

NGINX 使用提供的 SSL 证书设置 SSL 终止：

/etc/nginx/nginx.conf

```
http {

    server {

        listen 443 ssl;

        server_name www.test.com;

        ssl_certificate /etc/nginx/ssl/website.com/certificate.crt;

        ssl_certificate_key /etc/nginx/ssl/website.com/private.key;

        location /ip {

            proxy_pass http://httpbin.org:80;

        }

    }

}
```

❶ 在端口 443 上监听 HTTPS 请求。

❷ 配置 SSL 证书路径。

❸ 配置 SSL 证书密钥路径。

APISIX 使用 SSL 证书对象来存储证书和私钥。创建对象前，使用 [jq](https://jqlang.org/) 将 PEM 文件编码为 JSON 字符串。`jq` 输出的 `$cert` 和 `$key` 已包含两侧引号，因此在请求正文中不要再次为变量加引号：

```
cert=$(jq -Rs . < certificate.crt)

key=$(jq -Rs . < private.key)



curl -i "http://127.0.0.1:9180/apisix/admin/ssls" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" --data-binary @- <<EOF

{

  "id": "apisix-test-com-ssl",

  "sni": "www.test.com",

  "cert": $cert,

  "key": $key

}

EOF
```

❶ 配置 SSL 证书。

❷ 配置 SSL 证书密钥。

请参阅 [配置客户端和 APISIX 之间的 HTTPS](https://docs.apiseven.com/apisix/how-to-guide/traffic-management/tls-and-mtls/configure-https-between-client-and-apisix.md) 以获取有关配置 SSL 的详细指南。

### 将 HTTP 重定向到 HTTPS[​](#将-http-重定向到-https "将 HTTP 重定向到 HTTPS的直接链接")

除了终止 HTTPS 流量外，还可以配置 NGINX 将 HTTP 流量重定向到 HTTPS。

NGINX 使用 `return` 指令通过 `301 Moved Permanently` 状态代码进行重定向：

/etc/nginx/nginx.conf

```
http {

    server {

        listen 80;

        server_name www.test.com;

        return 301 https://$host$request_uri;

    }

}
```

❶ 重定向到请求 URI 的 HTTPS 版本。

APISIX 使用 `redirect` 插件来实现相同的行为：

```
curl -i "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" -d '

{

    "id": "apisix-redirect",

    "uri": "/*",

    "plugins": {

        "redirect": {

            "http_to_https": true,

            "ret_code": 301

        }

    }

}'
```

❶ 将 HTTP 请求重定向到 HTTPS。

❷ 在重定向时返回 `301 Moved Permanently` 状态代码。

向路由发送 HTTP 请求：

```
curl -i "http://127.0.0.1:9080/anything"
```

你应该看到 `HTTP/1.1 301 Moved Permanently` 响应。

## 配置 IP 访问控制[​](#配置-ip-访问控制 "配置 IP 访问控制的直接链接")

使用 NGINX 作为防火墙的一种方法是限制特定 IP 地址对你的服务的访问。这有助于防止未经授权的访问和恶意用户。

此示例使用 NGINX 和 APISIX 仅允许来自 IP 地址 `192.168.1.0/24` 的请求。

NGINX 使用 `allow` 指令允许访问 IP 地址，使用 `deny` 指令拒绝访问，如下所示：

/etc/nginx/nginx.conf

```
http {

    server {

        listen 80;

        location /anything/ {

            allow 192.168.1.0/24;

            deny all;

            proxy_pass http://httpbin.org:80;

        }

    }

}
```

❶ 允许访问 IP 地址 `192.168.1.0/24`。

❷ 拒绝所有其他 IP 地址的访问。

APISIX 通过 [`ip-restriction`](https://docs.apiseven.com/hub/ip-restriction.md) 插件实现相同的配置。

创建一个启用 `ip-restriction` 的路由：

```
curl -i "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" -d '

{

  "id": "apisix-anything",

  "uri": "/anything",

  "plugins": {

    "ip-restriction": {

      "whitelist": ["192.168.1.0/24"]

    }

  },

  "upstream": {

    "type": "roundrobin",

    "nodes": {

      "httpbin.org:80": 1

    }

  }

}'
```

❶ 将 IP 地址 `192.168.1.0/24` 添加到白名单以允许访问。

向创建的路由发送请求：

```
curl -i "http://127.0.0.1:9080/anything"
```

如果你的 IP 被允许，你应该收到 `HTTP/1.1 200 OK` 响应。如果没有，你应该收到 `HTTP/1.1 403 Forbidden` 响应和以下错误消息：

```
{"message":"Your IP address is not allowed"}
```

## 自定义 APISIX 生成的 NGINX 配置[​](#自定义-apisix-生成的-nginx-配置 "自定义 APISIX 生成的 NGINX 配置的直接链接")

APISIX 根据 [`apisix/cli/config.lua`](https://github.com/apache/apisix/blob/3.20.0/apisix/cli/config.lua) 中的配置生成 NGINX 配置文件。要自定义 NGINX 配置，请将代码片段添加到 `conf/config.yaml` 文件的 `nginx_config` 字段中。

下面的示例展示了可用的代码片段和示例：

```
nginx_config:

  main_configuration_snippet: |

    daemon on;

  http_configuration_snippet: |

    log_format admin "$request_time $pipe";



    server

    {

        listen 45651;

        server_name _;

        access_log off;



        location /ysec_status {

            req_status_show;

            allow 127.0.0.1;

            deny all;

        }

    }



    chunked_transfer_encoding on;

  http_server_configuration_snippet: |

    set $my "var";

  http_admin_configuration_snippet: |

    access_log logs/admin_access.log admin;

  http_end_configuration_snippet: |

    server_names_hash_bucket_size 128;

  stream_configuration_snippet: |

    tcp_nodelay off;
```

❶ 将自定义指令添加到 `main` 上下文（在其他上下文之外）。

❷ 将自定义配置添加到 `http` 上下文。

❸ 将自定义指令添加到 `server` 上下文。

❹ 将自定义指令添加到 `admin` `server` 上下文。

❺ 将自定义指令添加到 `http` 上下文的末尾。

❻ 将自定义配置添加到 `stream` 上下文。

警告

确保正确缩进自定义配置。不正确的缩进可能会导致 APISIX 在生成 NGINX 配置时失败。

## 常见问题解答和故障排除[​](#常见问题解答和故障排除 "常见问题解答和故障排除的直接链接")

### HTTP 请求自动重定向到 HTTPS，状态代码为 `HTTP/1.1 301 Moved Permanently` 或 `HTTP/1.1 308 Permanent Redirect`[​](#http-请求自动重定向到-https状态代码为-http11-301-moved-permanently-或-http11-308-permanent-redirect "http-请求自动重定向到-https状态代码为-http11-301-moved-permanently-或-http11-308-permanent-redirect的直接链接")

APISIX 不会强制将 `301` 重定向到 HTTPS，除非如 [上节](#%E5%B0%86-http-%E9%87%8D%E5%AE%9A%E5%90%91%E5%88%B0-https) 所示配置了 `redirect` 插件。

如果你打算在同一个域上同时支持 HTTP 和 HTTPS，则无需配置启用了 `http_to_https` 的 `redirect` 插件。
