developer tip

서버 응답 헤더 IIS7 제거

optionbox 2020. 8. 14. 07:39
반응형

서버 응답 헤더 IIS7 제거


IIS7에서 "서버"응답 헤더를 제거하는 방법이 있습니까? HttpModules를 사용하여 동일한 결과를 얻을 수 있음을 보여주는 기사가 있습니다. 서버에 대한 관리자 권한이없는 경우 유용합니다. 또한 ISAPI 필터를 작성하고 싶지 않습니다.

내 서버에 대한 관리자 권한이 있습니다. 그래서 저는 위의 것들을하고 싶지 않습니다. 그러니 저도 그렇게하도록 도와주세요.


이것을 global.asax.cs에 추가하십시오.

protected void Application_PreSendRequestHeaders()
{
    Response.Headers.Remove("Server");
    Response.Headers.Remove("X-AspNet-Version");
    Response.Headers.Remove("X-AspNetMvc-Version");
}

IIS7에서는 HTTP 모듈을 사용해야합니다. 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");
    }
  }
}

그런 다음 web.config에 다음을 추가하거나 IIS 내에서 구성합니다 (IIS 내에서 구성하는 경우 어셈블리는 GAC에 있어야 함).

<configuration>
  <system.webServer>
    <modules>
      <add name="CustomHeaderModule"
       type="StrongNamespace.HttpModules.CustomHeaderModule" />
    </modules>
  </system.webServer>
</configuration>

IIS 용 URL 재 작성 모듈 버전 2.0 (UrlRewrite)이 활성화 된 상태에서 구성 섹션에서 <configuration><system.webServer><rewrite>아웃 바운드 규칙을 추가합니다.

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

Scott Mitchell은 블로그 게시물에서 불필요한 헤더제거하는 솔루션을 제공합니다 .

다른 답변에서 이미 언급했듯이 Server헤더의 경우 http 모듈 솔루션 또는 UrlScan 모듈이 있습니다. (URLScan 모듈은 IIS7.5 +에서 더 이상 사용할 수 없습니다. 대신 URLRewrite를 사용하여 공백을 만드십시오 .)

의 경우 X-AspNet-VersionX-AspNetMvc-Version단순히 모든 그들을 생성 : 그는 각 응답에 그들을 제거하는 것보다 더 나은 방법을 제공합니다.

web.config에서 enableVersionHeader비활성화에 사용X-AspNet-Version

<httpRuntime enableVersionHeader="false" />

MvcHandler.DisableMvcResponseHeader비활성화를 위해 .Net Application_Start 이벤트에서 사용X-AspNetMvc-Version

MvcHandler.DisableMvcResponseHeader = true;

마지막으로 IIS 구성에서 X-Powered-By사용자 지정 헤더를 제거 합니다. (이는 web.config에서 수행 할 수 있습니다. configuration/system.webServer/httpProtocol/customHeaders/remove[name=X-Powered-By])

ARR (Application Request Routing)이있는 경우 X-Powered-By사용자 지정 헤더 설정으로 제거되지 않는 자체를 추가합니다 . 이것은 IIS 관리자, IIS 루트 (사이트가 아님)의 편집기 구성을 통해 제거 해야 합니다. system.webServer/proxy노드 로 이동하여로 설정 arrResponseHeader합니다 false. 뒤에는 IISReset고려됩니다.
( 이 게시물은 이전 IIS 6.0 구성 방법에 관한 것 외에는 여기 에서 찾았 습니다.)

애플리케이션 코드 별 솔루션은 기본적으로 정적 콘텐츠에서 생성 된 헤더에 적용되지 않는다는 점을 잊지 마십시오 ( runAllManagedModulesForAllRequests이를 변경 하기 위해 활성화 할 수 있지만 모든 요청이 .Net 파이프 라인을 실행하게 함). X-AspNetMvc-Version정적 콘텐츠에 추가되지 않기 때문에 문제 가되지 않습니다 (적어도 정적 요청이 .Net 파이프 라인에서 실행되지 않는 경우).

참고 : 사용 된 기술을 은폐하는 것이 목표 인 경우 표준 .Net 쿠키 이름도 변경해야합니다 ( .ASPXAUTH양식 인증이 활성화 된 경우 ( web.config name에서 forms태그의 속성 사용 ), ASP.NET_SessionId( 태그 <sessionState cookieName="yourName" />아래의 web.config에서 사용 system.web), __RequestVerificationToken(변경 을 사용하는 코드에 의해 AntiForgeryConfig.CookieName, 그러나 안타깝게도이 시스템이 html에서 생성하는 숨겨진 입력에는 적용되지 않습니다)).


실제로 위에 표시된 코딩 된 모듈과 Global.asax 예제는 유효한 요청에 대해서만 작동합니다.

예를 들어, URL 끝에 <를 추가하면 여전히 서버 헤더를 노출하는 "잘못된 요청"페이지가 표시됩니다. 많은 개발자들이 이것을 간과합니다.

표시된 레지스트리 설정도 작동하지 않습니다. URLScan은 "서버"헤더를 제거하는 유일한 방법입니다 (적어도 IIS 7.5에서는).


또는 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>

URL 재 작성 답변에 대한 추가 , 여기에 대한 완전한 XML이 있습니다.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 재 작성


Server:헤더 를 제거하려면 로 이동 Global.asax하여 Application_PreSendRequestHeaders이벤트를 찾아서 생성 한 후 다음과 같이 줄을 추가하십시오 ( BK이 블로그 덕분에 Cassini / 로컬 개발자에서도 실패하지 않습니다).

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");
        }
    }
}

Azure / IIS7에서 모든 관련 헤더를 제거하고 Cassini에서도 작동하는 완전한 솔루션을 원하면 HttpModules 또는 URLScan을 사용하지 않고 이러한 헤더를 비활성화하는 가장 좋은 방법을 보여주는 이 링크를 참조 하세요 .


web.config설정은 ASP.NET 응답에서 불필요한 헤더를 모두 제거합니다 (적어도 IIS 10부터 시작).

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

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

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

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.


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>

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


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


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.


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


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);


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/blog/easily-remove-unwanted-http-headers-in-iis-70-to-85

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"

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"

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

    protected void Application_PreSendRequestHeaders()
    {
        Response.Headers.Remove("Server");
    }

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.

참고URL : https://stackoverflow.com/questions/1178831/remove-server-response-header-iis7

반응형