<p>I've a Django application running behind Nginx ingress on Kubernetes. I wish to block requests that are sent with bad host headers (that are looking to do a host header exploit/cache poisoning).</p>

<p>To block these requests at the Nginx layer, I know I can add a server block with the <code>default_server</code> parameter as described <a href="https://stackoverflow.com/a/47851675/131050">here</a>.</p>

<p>However, I am not sure how to do that in Kubernetes via the externalingress yaml. I came across this <a href="https://github.com/kubernetes/ingress-nginx/issues/85" rel="nofollow noreferrer">PR</a> which seemed relevant, but could not figure it out.</p>

jeffreyveon
<p>You can do that in two ways: via <code>server-snippet</code> <a href="https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/#server-snippet" rel="nofollow noreferrer">annotation</a> or by overriding existing Nginx Ingress Controller's <a href="https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/configmap/#configmaps" rel="nofollow noreferrer">ConfigMap</a>.</p>

<p>Example from documentation, how to update server configuration block in related <code>nginx.conf</code> file for underlying <code>nginx-ingress-controller</code> Pod via <code>server-snippet</code> annotation:</p>

<pre><code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    nginx.ingress.kubernetes.io/server-snippet: |
        set $agentflag 0;

        if ($http_user_agent ~* "(Mobile)" ){
          set $agentflag 1;
        }

        if ( $agentflag = 1 ) {
          return 301 https://m.example.com;
        }
</code></pre>

<p>ConfigMap requires also <code>server-snippet</code> parameter in order to propagate configuration to <code>nginx-ingress-controller</code> Pod:</p>

<pre><code>kind: ConfigMap
apiVersion: v1
metadata:
  name: ingress-nginx-ingress-controller
  namespace: ingress-nginx
data:
  server-snippet: |
    set $agentflag 0;

        if ($http_user_agent ~* "(Mobile)" ){
          set $agentflag 1;
        }

        if ( $agentflag = 1 ) {
          return 301 https://m.example.com;
        }
</code></pre>
