3

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'
)
3
  • Why you want to remove this header? Commented May 23, 2018 at 17:32
  • @SHIVAMJINDAL, because it gives sensible information, for example: Server: WSGIServer/0.2 CPython/3.5.3 Commented May 23, 2018 at 17:35
  • This should be done in server config file imho. In example for nginx you should look for proxy_set_header Commented May 24, 2018 at 19:40

1 Answer 1

3

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".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.