You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Apache RewriteRule迁移至K8s Nginx Ingress Controller遇阻求助

Apache Rewrite规则迁移至Kubernetes Nginx Ingress Controller

规则转换说明

原Apache配置针对/var/www/html/motos目录下的请求,将包含任意字符+Portal前缀的路径重写至/motos/auto_portal/对应子路径。需通过Nginx Ingress的nginx.ingress.kubernetes.io/configuration-snippet注解插入自定义rewrite规则,实现等效逻辑。

完整Ingress配置

---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: motos-site
  annotations:
    # 插入Nginx重写规则,实现与Apache RewriteRule等效逻辑
    nginx.ingress.kubernetes.io/configuration-snippet: |
      rewrite ^/.+Portal/index.php(.*)$ /motos/auto_portal/index.php$1 last;
      rewrite ^/.+Portal/private/?(.*)$ /motos/auto_portal/private/$1 last;
      rewrite ^/.+Portal/scripts/?(.*)$ /motos/auto_portal/scripts/$1 last;
      rewrite ^/.+Portal/graphics/?(.*)$ /motos/auto_portal/graphics/$1 last;
spec:
  rules:
  - host: your-host.com  # 替换为实际域名
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: motos-service  # 替换为你的服务名称
            port:
              number: 80  # 替换为服务暴露的端口

关键配置解释

  1. 注解部分:

    • configuration-snippet用于注入自定义Nginx配置片段,直接将Apache的RewriteRule转换为Nginx的rewrite指令。
    • 正则表达式与Apache兼容,仅去掉了可选的/?前缀(Nginx请求URI始终以/开头)。
    • last标记:匹配规则后停止后续rewrite处理,等效于Apache的[L]标记,提升处理效率。
  2. 路径匹配:

    • 设置path: /和pathType: Prefix,确保所有发往该域名的请求都经过重写规则处理。若服务仅需处理/motos/开头的请求,可将path改为/motos/以缩小匹配范围。

可选调整

  • 若需浏览器地址栏显示重写后的路径,将last替换为permanent(301永久重定向)或redirect(302临时重定向)。
  • 验证配置:执行kubectl exec -it <nginx-ingress-controller-pod-name> -- nginx -T,查看生成的Nginx配置确认规则已加载。

内容的提问来源于stack exchange,提问作者prosto.vint

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 14:18:15