Nicky
Nicky

Reputation: 3817

Kubernetes Ingress - How to rewrite all non-www traffic to www subdomain?

I have a Kubernetes Ingress resource where I'm trying to redirect all non-www traffic to www subdomain for url canonicalization. So all traffic on example.com should be rewritten to www.example.com. I can't seem to figure out how to use the Ingress rewrite example properly to achieve this.

My Ingress (JSON format):

{
  "apiVersion": "extensions/v1beta1",
  "kind": "Ingress",
  "metadata": {
    "name": "example-staging",
    "annotations": {
      "ingress.kubernetes.io/rewrite-target": "/",
      "kubernetes.io/ingress.global-static-ip-name": "example-static-ip"
    }
  },
  "spec": {
    "rules": [
      {
        "host": "www.example.nl",
        "http": {
          "paths": [
            {
              "path": "/",
              "backend": {
                "serviceName": "example-service",
                "servicePort": 80
              }
            }
          ]
        }
      }
    ]
  }
}

Upvotes: 2

Views: 1811

Answers (1)

coreypobrien
coreypobrien

Reputation: 2041

The ingress.kubernetes.io/rewrite-target is used for rewriting the request URI, not the host.

It looks like from your link you're using the nginx ingress controller. You can get the effect you want by adding a second Ingress for example.nl that uses the ingress.kubernetes.io/configuration-snippet annotation to add the 301.

{
  "apiVersion": "extensions/v1beta1",
  "kind": "Ingress",
  "metadata": {
    "name": "example-staging-wwwredir",
    "annotations": {
      "ingress.kubernetes.io/rewrite-target": "/",
      "ingress.kubernetes.io/configuration-snippet": "return 301 $scheme://www.example.nl$request_uri;"
    }
  },
  "spec": {
    "rules": [
      {
        "host": "example.nl",
        "http": {
          "paths": [
            {
              "path": "/",
              "backend": {
                "serviceName": "example-service",
                "servicePort": 80
              }
            }
          ]
        }
      }
    ]
  }
}

Upvotes: 2

Related Questions