Remove Server Response Header IIS7
Asked Answered
P

20

124

Is there any way to remove "Server" response header from IIS7? There are some articles showing that using HttpModules we can achieve the same thing. This will be helpful if we don't have admin right to server. Also I don't want to write ISAPI filter.

I have admin rights to my server. So I don't want to do the above stuff. So, please help me to do the same.

Pneumograph answered 24/7, 2009 at 16:47 Comment(1)
See: #22401719Byplay
M
125

Add this to your global.asax.cs:

protected void Application_PreSendRequestHeaders()
{
    Response.Headers.Remove("Server");
    Response.Headers.Remove("X-AspNet-Version");
    Response.Headers.Remove("X-AspNetMvc-Version");
}
Miracidium answered 7/9, 2011 at 18:5 Comment(13)
I tried the registry option from @Richard above with no luck. I'm using Win 2008 R2 and the registry key was missing so I added a new DWORD key, which may have been incorrect. This option worked perfectly though. Thanks!Sleekit
Don't know why the http module answer is higher than this one, this one is much easierMallissa
This is the simplest method I've found to remove the 'Server' header from IIS7 responses. Thanks.Seismic
This should be the preferred answer. very small changeDesdee
For me it is displaying an error "Object reference not set to an instance of an object" I am stuck hereGillam
You might find you get a NullReferenceException in Cassini if you rely on HttpContext.Current. This blog post shows how to do so whilst avoiding breaking Cassini support, if that is important to you.Berrie
Weirdly, given this worked for me in September, this is no longer working for me. I can only assume one of the recent Windows Updates messed with it (presumably the one that also added net.tcp and other bindings the other day.Berrie
@PsychoDad this works for ASP.NET requests only, not for static files like .css and .jsDavilman
Using IIS 8.0, I'm only seeing the Server header on ASP.NET requests, but not on static files. When I add Response.Headers.Remove("Server"); I don't get the Server header at all.Simulate
To get rid of the MVC header you can do this MvcHandler.DisableMvcResponseHeader = true;Outwit
It is not a good idea to use the PreSendRequestHeaders in a class that implements IHttpModule or Global.asax. I have witnessed the event freezing the app on the server under stress load. The BeginRequest event should work to make response header changes. See hanselman.com/blog/ChecklistWhatNOTToDoInASPNET.aspx .Reclamation
Can put this in EndRequest instead if you prefer, may avoid above freeze risk under load: protected void Application_EndRequest(object sender, EventArgs ev) { Response.Headers.Remove("Server"); }Snappish
As noted in other answers there are problems with this approach (e.g. error requests are not affected). It seems that from IIS10+ there is a way to remove this headers for good with web.config: https://mcmap.net/q/179871/-remove-server-response-header-iis7Blagoveshchensk
N
78

In IIS7 you have to use an HTTP module. Build the following as a class library in VS:

namespace StrongNamespace.HttpModules
{
  public class CustomHeaderModule : IHttpModule
  { 
    public void Init(HttpApplication context)
    {
      context.PreSendRequestHeaders += OnPreSendRequestHeaders;
    } 

    public void Dispose() { } 

    void OnPreSendRequestHeaders(object sender, EventArgs e)
    {
      HttpContext.Current.Response.Headers.Set("Server", "Box of Bolts");
    }
  }
}

Then add the following to your web.config, or you configure it within IIS (if you configure within IIS, the assembly must be in the GAC).

<configuration>
  <system.webServer>
    <modules>
      <add name="CustomHeaderModule"
       type="StrongNamespace.HttpModules.CustomHeaderModule" />
    </modules>
  </system.webServer>
</configuration>
Nudge answered 29/7, 2009 at 16:10 Comment(11)
Excellent, I can also tweak this to remove the ETag header across my server farm.Alpine
This causes a runtime error in casini... / ASP.NET Dev serverChew
Modifying header values requires IIS7 Integrated Mode, however the exception is ignored unless another exception is thrown in the context of the request. Per the title, the question was targeted at IIS7, not casini.Nudge
@Chew The ASP.Net dev server (Cassini) won't like that code; this blog post has a solution to it, though — you need to check that the HttpApplication, the HttpRequest, the HttpContext, and the HttpResponse are not null, as well as checking that HttpRequest.IsLocal is false.Berrie
Weirdly, given this worked for me in September, this is no longer working for me. I can only assume one of the recent Windows Updates messed with it (presumably the one that also added net.tcp and other bindings the other day.Berrie
As modifying the header in PreSendRequestHeaders could cause issues with HttpCacheModule, you should use something like PostReleaseRequestState instead.Mariannmarianna
The module is not invoked when IIS sends 304 Not Modified header for static files (css / less / images / etc) as this does not reach the ASP.NET pipeline, so in this situation Server: Microsoft IIS/7.5 is still renderedMammalian
This page is a top result for Google search "server "box of bolts"", so don't forget to change it to something unique or simply remove it by HttpContext.Current.Response.Headers.Remove("Server");Pincince
Note: if you use it with GAC you should write it with the full qualified name like "StrongNamespace.HttpModules.CustomHeaderModule, StrongNamespace, Version=4.2.0.0, Culture=neutral, PublicKeyToken=31FF3856AF364G35"Kuhlmann
Warning: using HttpContext.Current.Response instead of Response property may cause a NullReferenceException!Scraggy
As noted in other answers there are problems with this approach (e.g. error requests are not affected). It seems that from IIS10+ there is a way to remove this headers for good with web.config: https://mcmap.net/q/179871/-remove-server-response-header-iis7Blagoveshchensk
T
69

Scott Mitchell provides in a blog post solutions for removing unnecessary headers.

As already said here in other answers, for the Server header, there is the http module solution, or a web.config solution for IIS 10+, or you can use URLRewrite instead for blanking it.

For this Server header, the most practical solution for an up-to-date (IIS 10 +) setup is using removeServerHeader in the web.config:

<system.webServer>
  ...
  <security>
    <requestFiltering removeServerHeader="true" />
  </security>
  ...
</system.webServer>

For X-AspNet-Version and X-AspNetMvc-Version, Scott Mitchell provides a better way than removing them on each response: simply not generating them at all.

Use enableVersionHeader for disabling X-AspNet-Version, in web.config

<system.web>
  ...
  <httpRuntime enableVersionHeader="false" />
  ...
</system.web>

Use MvcHandler.DisableMvcResponseHeader in .Net Application_Start event for disabling X-AspNetMvc-Version

MvcHandler.DisableMvcResponseHeader = true;

And finally, remove in IIS configuration the X-Powered-By custom header in web.config.

<system.webServer>
  ...
  <httpProtocol>
    <customHeaders>
      <remove name="X-Powered-By" />
    </customHeaders>
  </httpProtocol>
  ...
</system.webServer>

Beware, if you have ARR (Application Request Routing), it will also add its own X-Powered-By, which will not be removed by custom headers settings. This one has to be removed through the IIS Manager, Editor configuration on the IIS root (not on a site): go to system.webServer/proxy node and set arrResponseHeader to false. After an IISReset, it is taken into account.
(I have found this one here, excepted this post is about old IIS 6.0 way of configuring things.)

Do not forget that solution by application code does not apply by default to header generated on static content (you may activate the runAllManagedModulesForAllRequests for changing that, but it causes all requests to run .Net pipeline). It is not an issue for X-AspNetMvc-Version since it is not added on static content (at least if static request are not run in .Net pipeline).

Side note: when the aim is to cloak used technology, you should also change standard .Net cookie names (.ASPXAUTH if forms auth activated (use name attribute on forms tag in web.config), ASP.NET_SessionId (use <sessionState cookieName="yourName" /> in web.config under system.web tag), __RequestVerificationToken (change it by code with AntiForgeryConfig.CookieName, but unfortunately does not apply to the hidden input this system generates in the html)).

Thready answered 11/7, 2013 at 18:9 Comment(11)
I added this code <security> <requestFiltering removeServerHeader ="true" /> <requestFiltering> <denyUrlSequences> <add sequence="xmlrpc.php" /> </denyUrlSequences> </requestFiltering> </security> once I added "requestFiltering" server error appears. If i remove "requestFiltering " it works fine. I want to hide IIS and it's version discloser. My IIS is 10.0. What should I do? ThanksAustralian
Comments are not suitable for answering questions, better ask another question, after having double checked you meet the requirements documented by Microsoft. (My answer links toward this documentation.)Petr
<requestFiltering removeServerHeader="true" /> -> This gives warning "attribute" is not allowed.Nattie
@AshishShukla, this is not the case in VS2019. Update your configuration schema in your current IDE.Petr
Thanks, <httpRuntime enableVersionHeader="false" /> works for me. I am using IIS 10. The URL Rewrite rule I had seems to have broken since upgrading to IIS 10.Angst
The question was for IIS 7 and this doesn't work in IIS 7Fugate
Most of the answer does work with IIS7 and the parts which do not are properly highlighted.Petr
I'm sorry but posting a solution for IIS 10 in a topic that is specifically about IIS 7 warrants downvoting.Sismondi
I still cannot get it. Outdated content is a plague. I intend to go-on completing my answers to keep them up-to-date, in the same way I have done here: mentioning from which version it applies and keeping older solutions mentioned. The sentence right above the IIS 10+ solution for the Server header is about them, linking toward other answers addressing this point for IIS < 10. What would be the alternative? Duping the question for each new version of IIS? It would cause the optimal answers for each reader case to be quite harder to find.Petr
Is there a way to make an older version of IIS just ignore these IIS 10 only attributes? If I add them into the web.config, the web app won't start using IIS 8 :(Drab
Not that I know of. If you have to use the same web.config for different IIS versions, you have to use only features supported by the lowest one.Petr
I
46

With the URL Rewrite Module Version 2.0 for IIS (UrlRewrite) enabled, in the configuration section <configuration><system.webServer><rewrite> add the outbound rule:

<outboundRules>
  <rule name="Remove RESPONSE_Server" >
    <match serverVariable="RESPONSE_Server" pattern=".+" />
    <action type="Rewrite" value="" />
  </rule>
</outboundRules>
Indecorous answered 27/9, 2012 at 7:10 Comment(8)
Note that this only blanks the Server header, it does not remove it.Handout
Sorry for the ignorance but to which part should I add this in ?! I tried adding it inside <system.webServer>Ferous
Thanks! Works in IIS 8.5, this is so easy. I don't have a text editor but you can easily use the GUI. The name should be RESPONSE_Server, not just Server (this is where I failed at first).Defilade
this is good enough if you got a non-ASP.Net application therefor you can't remove server header with mentioned codesIgnominious
@vignesh this is some UrlRewrite config subnodes. You have to put them under a rewrite node in system.webServer. Beware, this will crash your site if UrlRewrite is not installed on the server. And you'd better use the IIS configuration console first to check how it write down those config nodes.Petr
if 500 Internal Server Error occurs for the configured website it is revealing server info.Can anyone help on thisWhoop
You can now get rid of Server response for good. At least from IIS10+ there is a way to remove this headers with web.config: https://mcmap.net/q/179871/-remove-server-response-header-iis7Blagoveshchensk
the question was for IIS7 and the rest of the responses did not work in IIS7 as the other people even said they were for IIS10. this one worked. good stuff +1Fugate
B
25

This web.config setup works to remove all unnecessary headers from the ASP.NET response (at least starting from IIS 10):

<system.web>
    <!-- Removes version headers from response -->
    <httpRuntime enableVersionHeader="false" />
</system.web>

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <!--Removes X-Powered-By header from response -->
            <clear />
        </customHeaders>
    </httpProtocol>

    <security>
        <!--Removes Server header from response-->
        <requestFiltering removeServerHeader ="true" />
    </security>
</system.webServer>

Please note that this hides all the headers for the "application", as do all the other approaches. If you e.g. reach some default page or an error page generated by the IIS itself or ASP.NET outside your application these rules won't apply. So ideally they should be on the root level in IIS and that sill may leave some error responses to the IIS itself.

P.S. There is a bug in IIS 10 that makes it sometimes show the server header even with correct config. It should be fixed by now, but IIS/Windows has to be updated.

Blagoveshchensk answered 9/11, 2018 at 9:24 Comment(4)
<requestFiltering removeServerHeader="true" /> This gives warning "attribute is not allowed".Nattie
Thank you, this was exactly what I'm looking for!Insouciance
I'm sorry but posting a solution for IIS 10 in a topic that is specifically about IIS 7 warrants downvoting.Sismondi
Is there a way to make IIS 7 ignore these IIS 10 only attributes? If I add them to the web.config, the web app will be unable to start with IIS 7 :(Drab
M
22

Actually the coded modules and the Global.asax examples shown above only work for valid requests.

For example, add < on the end of your URL and you will get a "Bad request" page which still exposes the server header. A lot of developers overlook this.

The registry settings shown do not work either. URLScan is the ONLY way to remove the "server" header (at least in IIS 7.5).

Mchale answered 15/2, 2013 at 11:0 Comment(4)
It's working for me with the coded module (added in web.config) even on an bad request ;) In global.asax it's not really working (e.g. static files etc.)Peroxide
Lets hope you still have request validation switched on.Mchale
does anyone have an alternative to urlscan for IIS 8+?Padnag
There is a working solution at least in IIS10+: https://mcmap.net/q/182087/-remove-server-response-header-iis-8-0-8-5Blagoveshchensk
R
18

Or add in web.config:

<system.webServer>
    <httpProtocol>
        <customHeaders>
            <remove name="X-AspNet-Version" />
            <remove name="X-AspNetMvc-Version" />
            <remove name="X-Powered-By" />
            <!-- <remove name="Server" />  this one doesn't work -->
        </customHeaders>
    </httpProtocol>
</system.webServer>
Roussillon answered 29/10, 2013 at 13:40 Comment(4)
This method doesn't remove the 'Server' header. The others are removed.Devitalize
You can get rid of the X-Powered-By in the Response headers configuration on the server level.Maturation
I don't know if there is a cases where this way removes X-AspNet-Version and X-AspNetMvc-Version header. What I know is this way does not always work (if it ever works). See @Frederic answer for a more reliable way to remove them.Cymatium
There is a way now in IIS10+ to remove the server header: https://mcmap.net/q/179871/-remove-server-response-header-iis7Blagoveshchensk
A
13

Addition to the URL Rewrite answer, here is the complete XML for web.config

<system.webServer>
  <rewrite>
    <outboundRules>
      <rule name="Remove RESPONSE_Server" >
        <match serverVariable="RESPONSE_Server" pattern=".+" />
        <action type="Rewrite" value="Company name" />
      </rule>
    </outboundRules>
  </rewrite>
</system.webServer>

URL Rewrite

Appealing answered 14/9, 2015 at 10:11 Comment(2)
Does this remove all IIS and ASP versions from hackerSousaphone
The above fix is working correctly for the web pages.But for images/icons if 500 Internal Server Error occurred it's showing the Server: Microsoft-IIS/7.5 instead of the value.Can you please help me on thisWhoop
H
11

To remove the Server: header, go to Global.asax, find/create the Application_PreSendRequestHeaders event and add a line as follows (thanks to BK and this blog this will also not fail on the Cassini / local dev):

protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
    // Remove the "Server" HTTP Header from response
    HttpApplication app = sender as HttpApplication;
    if (null != app && null != app.Request && !app.Request.IsLocal &&
        null != app.Context && null != app.Context.Response)
    {
        NameValueCollection headers = app.Context.Response.Headers;
        if (null != headers)
        {
            headers.Remove("Server");
        }
    }
}

If you want a complete solution to remove all related headers on Azure/IIS7 and also works with Cassini, see this link, which shows the best way to disable these headers without using HttpModules or URLScan.

Handout answered 9/10, 2012 at 16:49 Comment(0)
T
9

If you just want to remove the header you can use a shortened version of lukiffer's answer:

using System.Web;

namespace Site
{
    public sealed class HideServerHeaderModule : IHttpModule
    {
        public void Dispose() { }

        public void Init(HttpApplication context)
        {
            context.PreSendRequestHeaders +=
            (sender, e) => HttpContext.Current.Response.Headers.Remove("Server");
        }
    }
}

And then in Web.config:

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true">
    <add name="CustomHeaderModule" type="Site.HideServerHeaderModule" />
  </modules>
</system.webServer>
Tristich answered 26/6, 2011 at 12:29 Comment(2)
This is most appropriate because resources like css/js will not have the Server header, it ports from server to server without configuration and the Server response header won't just be empty, it will not be sent.Tanguy
I have seen comments that runAllManagedModulesForAllRequests="true" will slow down your app and is not recommended. Instead one could use urlrewrite module outboundRules to clear the server value also for static files. britishdeveloper.co.uk/2010/06/…Ira
A
5

Try setting the HKLM\SYSTEM\CurrentControlSet\Services\HTTP\Parameters\DisableServerHeader registry entry to a REG_DWORD of 1.

Agnola answered 12/10, 2009 at 16:8 Comment(3)
Ran into an odd situation with our server farm where this registry setting seems to be the only change that works across all of the OS's (W2K8, W2K3) we're using, for both IIS6 and IIS7.Configurationism
Frustratingly, this isn't making any difference for me, even after rebooting the virtual machine. We're running IIS 7.5 on Windows Server 2008 R2 Standard, "Version 6.1 (Build 7601: Service Pack 1)". Similarly, my OnPreSendRequestHeaders event handler (see above) is never firing, for some reason.Berrie
Unfortunately the registry key doesn't seem to work on IIS 7.5Driest
T
4

UrlScan can also remove the server header by using AlternateServerName= under [options].

Tatia answered 10/8, 2009 at 2:6 Comment(0)
H
2

Following up on eddiegroves' answer, depending on the version of URLScan, you may instead prefer RemoveServerHeader=1 under [options].

I'm not sure in which version of URLScan this option was added, but it has been available in version 2.5 and later.

Highgrade answered 2/9, 2011 at 18:15 Comment(0)
U
2

I found an article that explains why we need to do both Registry edit and use a tool such as UrlScan to set this up in IIS properly. I followed it on our servers and it works: http://blogs.msdn.com/b/varunm/archive/2013/04/23/remove-unwanted-http-response-headers.aspx. If you only use UrlScan but don't do the registry change, during the time you are stopping World Wide Publishing Service, your server will return server http response from the HTTP.sys file. Also, here are common pitfals of using UrlScan tool: http://msdn.microsoft.com/en-us/library/ff648552.aspx#ht_urlscan_008

Ultramarine answered 13/3, 2014 at 0:59 Comment(1)
Please post your code on Stack Overflow. Links can change and break, so posting code is much more helpfulVolscian
S
2

In IIS 10, we use a similar solution to Drew's approach, i.e.:

using System;
using System.Web;

namespace Common.Web.Modules.Http
{
    /// <summary>
    /// Sets custom headers in all requests (e.g. "Server" header) or simply remove some.
    /// </summary>
    public class CustomHeaderModule : IHttpModule
    {
        public void Init(HttpApplication context)
        {
            context.PreSendRequestHeaders += OnPreSendRequestHeaders;
        }

        public void Dispose() { }

        /// <summary>
        /// Event handler that implements the desired behavior for the PreSendRequestHeaders event,
        /// that occurs just before ASP.NET sends HTTP headers to the client.
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void OnPreSendRequestHeaders(object sender, EventArgs e)
        {
            //HttpContext.Current.Response.Headers.Remove("Server");
            HttpContext.Current.Response.Headers.Set("Server", "MyServer");
        }
    }
}

And obviously add a reference to that dll in your project(s) and also the module in the config(s) you want:

<system.webServer>
    <modules>
      <!--Use http module to remove/customize IIS "Server" header-->
      <add name="CustomHeaderModule" type="Common.Web.Modules.Http.CustomHeaderModule" />
    </modules>
</system.webServer>

IMPORTANT NOTE1: This solution needs an application pool set as integrated;

IMPORTANT NOTE2: All responses within the web app will be affected by this (css and js included);

Septet answered 4/7, 2017 at 10:55 Comment(0)
A
1

I had researched this and the URLRewrite method works well. Can't seem to find the change scripted anywhere well. I wrote this compatible with PowerShell v2 and above and tested it on IIS 7.5.

# Add Allowed Server Variable
    Add-WebConfiguration /system.webServer/rewrite/allowedServerVariables -atIndex 0 -value @{name="RESPONSE_SERVER"}
# Rule Name
    $ruleName = "Remove Server Response Header"
# Add outbound IIS Rewrite Rule
    Add-WebConfigurationProperty -pspath "iis:\" -filter "system.webServer/rewrite/outboundrules" -name "." -value @{name=$ruleName; stopProcessing='False'}
#Set Properties of newly created outbound rule 
    Set-WebConfigurationProperty -pspath "MACHINE/WEBROOT/APPHOST"  -filter "system.webServer/rewrite/outboundRules/rule[@name='$ruleName']/match" -name "serverVariable" -value "RESPONSE_SERVER"
    Set-WebConfigurationProperty -pspath "MACHINE/WEBROOT/APPHOST"  -filter "system.webServer/rewrite/outboundRules/rule[@name='$ruleName']/match" -name "pattern" -value ".*"
    Set-WebConfigurationProperty -pspath "MACHINE/WEBROOT/APPHOST"  -filter "system.webServer/rewrite/outboundRules/rule[@name='$ruleName']/action" -name "type" -value "Rewrite"
Apocarp answered 5/6, 2018 at 13:53 Comment(0)
T
1

You can add below code in Global.asax.cs file

    protected void Application_PreSendRequestHeaders()
    {
        Response.Headers.Remove("Server");
    }
Thrippence answered 6/6, 2019 at 9:55 Comment(0)
B
1

The solution proposed above in combination worked for me with following changes. Here I am posting my scenario and solution.

For me I wanted to remove the following headers:

  • Server
  • X-Powered-By
  • X-AspNet-Version
  • X-AspNetMvc-Version

I added these to my global.asax:

<%@ Application Language="C#" %>
<script runat="server">
    protected void Application_PreSendRequestHeaders()
    {
        Response.Headers.Remove("Server");
        Response.Headers.Remove("X-Powered-By");
        Response.Headers.Remove("X-AspNet-Version");
        Response.Headers.Remove("X-AspNetMvc-Version");
    }
</script>

The above event was not getting triggered, so for that I added following to web.config then it worked.

<modules runAllManagedModulesForAllRequests="true" />

and for removing version header I also added following to web.config:

<httpRuntime enableVersionHeader="false" />

Changes in web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true" />
    </system.webServer>
    <system.web>
        <httpRuntime enableVersionHeader="false" />
    </system.web>
</configuration>

Hope it helps!

Bailment answered 8/7, 2020 at 13:54 Comment(0)
E
0

I tried all of the stuff here and on several other similar stack overflow threads.

I got hung up for a bit because I forgot to clear my browser cache after making config changes. If you don't do that and the file is in your local cache, it will serve it back to you with the original headers (duh).

I got it mostly working by removing the runAllManagedModulesForAllRequests:

<modules runAllManagedModulesForAllRequests="true">

This removed the extraneous headers from most of the static files but I still was getting the "Server" header on some static files in my WebAPI project in swagger.

I finally found and applied this solution and now all of the unwanted headers are gone:

https://www.dionach.com/en-au/blog/easily-remove-unwanted-http-headers-in-iis-7-0-to-8-5/

which discusses his code that is here:

https://github.com/Dionach/StripHeaders/releases/tag/v1.0.5

This is a Native-Code module. It is able to remove the Server header, not just blank out the value. By default it removes:

  • Server
  • X-Powered-By
  • X-Aspnet-Version
  • Server: Microsoft-HTTPAPI/2.0 -- which would be returned if "the request fails to be passed to IIS"
Euphemism answered 20/2, 2018 at 21:16 Comment(0)
P
-1

IIS 7.5 and possibly newer versions have the header text stored in iiscore.dll

Using a hex editor, find the string and the word "Server" 53 65 72 76 65 72 after it and replace those with null bytes. In IIS 7.5 it looks like this:

4D 69 63 72 6F 73 6F 66 74 2D 49 49 53 2F 37 2E 35 00 00 00 53 65 72 76 65 72 

Unlike some other methods this does not result in a performance penalty. The header is also removed from all requests, even internal errors.

Piccard answered 24/9, 2019 at 13:6 Comment(1)
Yikes. Please let this be a joke.Dialyser

© 2022 - 2024 — McMap. All rights reserved.