Delete header in django rest framework response

I'm trying to delete Server header from django rest framework response, but I didn't find an easy way, so I create a middleware to delete it.

This is my first try:

middleware.py

class RemoveHeaders(object):
    def process_response(self, request, response):
        response['Server'] = ''
        return response

This middleware works ok, but the problem is that it fills server header with empty string and not delete it. so I tried the next:

class RemoveHeaders(object):
    def process_response(self, request, response):
        del response['Server']
        return response

But It doesn't work. server header continues.

How can I delete server header?, or do you know another alternative? thanks

Updated, these are my middlewares, maybe someone is override server header, case it doesn't exist?

MIDDLEWARE_CLASSES = (
    'corsheaders.middleware.CorsMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'my_api.middleware.RemoveHeaders'
)

Upvotes: 3

Views: 4143

Answers (1)

Patrik Beck
Patrik Beck

Reputation: 2505

I just had the exact same problem. Your approach with

del response['Server']

Is correct!

However, you need to move your middleware to be the first. As other middlewares will add headers after the response is constructed, so the order of application is bottom-up. Your middleware has to be the first one to have the "last word".

Upvotes: 3

Related Questions