动静分离:静态资源走/,动态接口走/api
nginx直接代理

    location / {
            proxy_pass http://web-portal/;
            proxy_redirect off;
            proxy_set_header Host host;
            proxy_set_header X-Real-Ipremote_addr;
            proxy_set_header X-Forwarded-For proxy_add_x_forwarded_for;
    }

    location /api/ {
            proxy_pass http://gateway:7000/;
            proxy_redirect off;
            proxy_set_header Hosthost;
            proxy_set_header X-Real-Ip remote_addr;
            proxy_set_header X-Forwarded-Forproxy_add_x_forwarded_for;
    }

使用ingress

错误的写法

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: www-test-com
  namespace: video
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/proxy-body-size: 10240m
    nginx.ingress.kubernetes.io/proxy-connect-timeout: "300"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "300"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "300"
spec:
  tls:
  - hosts:
    - www.test.net
    secretName: tls-www-test-com
  rules:
  - host: www.test.net
    http:
      paths:
      - path: /
        backend:
          serviceName: web-portal
          servicePort: 80
      - path: /api 
        backend:
          serviceName: gateway
          servicePort: 7000

此时静态访问正常,动态访问会报404,查看gateway日志发现/api被传到gateway里头去了,不识别。

正确写法

增加重定向nginx.ingress.kubernetes.io/rewrite-target: /$2
修改下path匹配/api(/|$)(.*)

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: www-test-com
  namespace: video
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /2
    nginx.ingress.kubernetes.io/proxy-body-size: 10240m
    nginx.ingress.kubernetes.io/proxy-connect-timeout: "300"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "300"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "300"
spec:
  tls:
  - hosts:
    - www.test.net
    secretName: tls-www-test-com
  rules:
  - host: www.test.net
    http:
      paths:
      - path: /
        backend:
          serviceName: web-portal
          servicePort: 80
      - path: /api(/|)(.*)
        backend:
          serviceName: gateway
          servicePort: 7000

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

Captcha Code