kubernetesnginxproxynginx-ingressingress-controller

How can I redirect to a different URL based on the source IPs in NGINX Ingress Controller


I have a set of IPs (Example: 1.1.1.1/24) and the requests coming from those source IPs (1.1.1.1/24) must redirect to a different URL. I tried the below method.

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-test
  annotations:
    nginx.ingress.kubernetes.io/server-snippet: |
        if ($http_x_forwarded_for != "1.1.1.1/24") {
        return 301 https://blablabla;
        }
spec:
  rules:
  - host: my-url
    http:
      paths:
      - path: /some-path-here
        backend:
          serviceName: some-service
          servicePort: 80

So when I do a curl https://my-url from one of the VMs inside 1.1.1.1/24 network it gives the below response which is correct.

curl -I https://my-url
HTTP/2 301 
date: Tue, 01 Aug 2023 06:34:31 GMT
content-type: text/html
content-length: 162
location: https://blablabla

But the issue is it redirects to https://blablabla from everywhere when I curl https://my-url not only from 1.1.1.1/24


Solution

  • I am not sure you'd be able to do this natively with the Kubernetes resources.

    You would be able to do this by setting up a proxy (httpd/apache/nginx) as a service the ingress talks to so it goes:

    internet -> loadbalancer -> ingress/ingress controller -> proxy -> backend service
    

    Then at the proxy you can do the redirect to bounce requests to the URL somewhere else upon any criteria you set.

    You may also be able to do this with something like a CDN in front of your service such as CloudFront or Google Cloud CDN, but YMMV. I know you can definitely do this with CDN services like Akamai, and probably with Fastly also.