<p>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 <code>example.com</code> should be rewritten to <code>www.example.com</code>. I can't seem to figure out how to use the <a href="https://github.com/kubernetes/contrib/tree/master/ingress/controllers/nginx/examples/rewrite" rel="nofollow noreferrer">Ingress rewrite example</a> properly to achieve this.</p>

<p>My Ingress (JSON format):</p>

<pre><code>{
  "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
              }
            }
          ]
        }
      }
    ]
  }
}
</code></pre>

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

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

<pre><code>{
  "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
              }
            }
          ]
        }
      }
    ]
  }
}
</code></pre>
