You need to enable JavaScript to run this app.
导航

Nginx Ingress 配置 URL 重写规则

最近更新时间2023.12.26 19:38:55

首次发布时间2023.12.26 19:38:55

Nginx Ingress 支持 URL 重写功能。本文为您介绍如何配置 Nginx Ingress 的 URL 重写功能。

背景说明

在某些应用场景中,后端服务提供的 URL 与 Nginx Ingress 规则中配置的路径不同。默认情况下,Nginx Ingress 将访问路径直接转发到后端服务中的相同路径,如果不配置 URL 重写规则,由于访问路径和服务路径不同,访问将返回404。此时,需要使用 URL 重写规则,改写服务访问的 URL,使其能够访问到后端服务的真实路径。

前提条件

操作步骤

Nginx Ingress 支持通过 Annotation 配置 URL 重写规则,示例和说明如下:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: nginx-ingress # 路由规则的名称
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: "/$2"
spec:
  ingressClassName: nginx # 指定 Ingress Controller
  rules:
  - host: example.com # 转发规则域名
    http:
      paths:
      - backend:
          service:
            name: service-demo # 请求被转发到的目标服务名称
            port:
              number: 80 # 请求被转发到的目标服务开放端口号
        path: /demo(/|$)(.*) # 访问路径
        pathType: ImplementationSpecific

Annotation 说明如下表所示。

Key类型是否必须描述默认值
nginx.ingress.kubernetes.io/rewrite-targetStringURL 重写的目标 URI,并使用正则表达式定义捕获组。

nginx.ingress.kubernetes.io/rewrite-target注解中,您可以使用正则表达式定义捕获组,例如本例中,$2表示将访问路径中,第二个括号(.*)中匹配到的所有字符填写到nginx.ingress.kubernetes.io/rewrite-target注解中。例如:

  • 请求example.com/demo会重写为example.com/
  • 请求example.com/demo/会重写为example.com/
  • 请求example.com/demo/test会重写为example.com/test

结果验证

查看配置

  1. 执行以下命令,查看 ingress 配置。
kubectl get ingress

预期返回结果如下,表示 Ingress 创建成功。

NAME            CLASS   HOSTS           ADDRESS           PORTS   AGE
nginx-ingress   nginx   example.com     180.xxx.xxx.xxx   80      74s

访问服务

由于后端服务默认的服务路径为/,而 Ingress 中配置的路径为/demo。当未配置 URL 重写规则时,由于路径不一致,直接通过 Ingress 访问服务时,返回404

curl -H "Host: example.com" http://180.xxx.xxx.xxx/demo

预期返回结果如下:

<html>
<head><title>404 Not Found</title></head>
<body>
<center><h1>404 Not Found</h1></center>
<hr><center>nginx</center>
</body>
</html>

当配置了 URL 重写规则后,使用以下命令访问服务。

curl -H "Host: example.com" https://180.xxx.xxx.xxx/demo

预期输出如下,能够正确地访问到后端服务。

<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>