Add custom response on 413 status code using the Nginx Ingress Controller

11/11/2019

I need to configure nginx to send a JSON response for 413 status code. I've tried this:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: {{ .Chart.Name }}-app2
  annotations:
    kubernetes.io/ingress.class: "nginx"
    ingress.kubernetes.io/server-snippet: |
      proxy_intercept_errors on;
      error_page 413 /413.json;
      location /413.json {
        return 413 '{"error": {"status_code": 413,"status": "TEST"}}';
      }
spec:
  tls:
  - hosts:
    - app2.example.com
    secretName: wildcard-tls
  rules:
  - host: app2.example.com
    http:
      paths:
      - path: /
        backend:
          serviceName: {{ .Chart.Name }}-app2
          servicePort: 80

but no success. It still returns html page with text 413 Request Entity Too Large.

Could you please suggest how to configure nginx in kubernetes to return json on 413?

-- Roman Marusyk
kubernetes
kubernetes-ingress
nginx
nginx-ingress

1 Answer

11/11/2019

You can try adding this snippet to ingress

nginx.ingress.kubernetes.io/server-snippet: |
      location @custom_413 {
        default_type application/json;
        return return 413 '{"error": {"status_code": 413,"status": "TEST"}}';;
      }
      error_page 413 @custom_413;
-- Harsh Manvar
Source: StackOverflow