Before I begin my question, I have referred the stackoverflow post - Delete header in django rest framework response.
Please find the middleware code and settings.py below (referred to the django middleware docs):
middleware.py:
class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
response = self.get_response(request)
response.__setitem__('Server', '')
return response
settings.py
MIDDLEWARE = [
....,
....,
'middleware_demo.middleware.SimpleMiddleware',
]
With the above code, I get the server response with the server header set to empty string as below. Which is as expected and doesn't disclose the server header details:
HTTP/1.1 200 OK
Date: Tue, 21 Apr 2020 12:55:25 GMT
Content-Type: text/html
Server:
X-Frame-Options: DENY
Content-Length: 16351
X-Content-Type-Options: nosniff
My goal is to remove the header altogether and tried 2 ways for the same in middleware.py:
Method 1 - official docs
class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
response = self.get_response(request)
response.__delitem__('Server')
return response
Method 2 - referred stackoverflow blog - Delete header in django rest framework response
class SimpleMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
response = self.get_response(request)
del response['Server']
return response
But the response still has the server header set and shows the version details too as below:
HTTP/1.1 200 OK
Date: Tue, 21 Apr 2020 13:00:26 GMT
Server: WSGIServer/0.2 CPython/3.6.5
Content-Type: text/html
X-Frame-Options: DENY
Content-Length: 16351
X-Content-Type-Options: nosniff
My question is why does the server header value get modified and comes up as empty string when modified, but when the header value itself is deleted, I'm seeing it in the response header. What is it that I'm missing here ?
Also, I have tried moving the middleware activation line to the first position and the last position, just in case something is being overriden. Still the same issue.
Your solution is right, except that you can't delete it or django will add it back. You must either make it blank or modify it...
response.headers['Server'] = "None of your beeswax!"
request header
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With