IIS 服务器配置
较旧的版本可能在 httpRuntime / TargetFramework 中包含与当前设置不匹配的配置。大多数配置取自更高版本,随后将用于提供可集成到您自己的配置中。
版本支持
服务器配置以 IIS7 +为目标,其中 IIS8(或简化版)可以使用替代配置,它将被标记。
web.config
请注意,此 web.config 适用于 IIS7,而不适用于 IIS6。
在 Microsoft IIS 服务器中,web.config 是允许 Web 服务器配置的配置文件。H5BP 团队已经确定了许多使网页快速安全的最佳实践服务器规则,这些规则可以通过配置 web.config 文件来应用。
web.config 文件中的许多设置都包含最佳做法,以提高 Web 性能。让我们深入研究文件并查看实践列表:
添加 Expires 或 Cache-Control 标头
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
上面的代码将静态内容的过期标头设置为 30 天。
网页设计越来越丰富,这意味着页面中将包含更多脚本,样式表,图像和 Flash。首次访问您的页面的访问者可能必须发出多个 HTTP 请求,但是通过使用 Expires 标头,您可以使这些组件可缓存。这避免了后续页面视图上不必要的 HTTP 请求。 Expires 标头最常与图像一起使用,但应在所有组件(包括脚本,样式表和 Flash 组件)上使用它们。
Gzip 组件
<httpCompression directory="%SystemDrive%\websites\_compressed" minFileSizeForComp="1024">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
<staticTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/javascript" enabled="true" />
<add mimeType="application/json" enabled="true" />
<add mimeType="*/*" enabled="false" />
</staticTypes>
</httpCompression>
GZip 静态文件内容。上面的代码覆盖了服务器默认值,该默认值仅通过将压缩的最小文件大小设置为 1024 来压缩 2700 字节以上的静态文件。
静态压缩
<urlCompression doStaticCompression="true" />
urlCompression 元素的 doStaticCompression 属性在站点,应用程序或文件夹级别启用静态内容压缩。
自定义 404 页面
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="404" redirect="404.html" />
</customErrors>
发生错误时,将自定义错误页面定义为 404.html,以显示自定义错误消息。
强制使用最新的 IE 版本
<add name="X-UA-Compatible" value="IE=Edge" />
强制使用最新的 IE 版本,在各种情况下(可能会退回到 IE7 模式)
使用 UTF-8 编码
<remove fileExtension=".css" />
<mimeMap fileExtension=".css" mimeType="text/css" />
<remove fileExtension=".js" />
<mimeMap fileExtension=".js" mimeType="text/javascript" />
<remove fileExtension=".json" />
<mimeMap fileExtension=".json" mimeType="application/json" />
<remove fileExtension=".rss" />
<mimeMap fileExtension=".rss" mimeType="application/rss+xml; charset=UTF-8" />
<remove fileExtension=".html" />
<mimeMap fileExtension=".html" mimeType="text/html; charset=UTF-8" />
<remove fileExtension=".xml" />
<mimeMap fileExtension=".xml" mimeType="application/xml; charset=UTF-8" />
对 RSS,HTML 和 XML 服务使用 UTF-8 编码的 text/plain 或 text/html。
添加 HTML5 视频的 MIME 类型
<mimeMap fileExtension=".mp4" mimeType="video/mp4" />
<mimeMap fileExtension=".m4v" mimeType="video/m4v" />
<mimeMap fileExtension=".ogg" mimeType="video/ogg" />
<mimeMap fileExtension=".ogv" mimeType="video/ogg" />
<mimeMap fileExtension=".webm" mimeType="video/webm" />
正确的SVG服务
对于 iPad 上的 SVG Webfonts 支持是必需的。
<mimeMap fileExtension=".svg" mimeType="images/svg+xml" />
<mimeMap fileExtension=".svgz" mimeType="images/svg+xml" />
HTML4 Web 字体 MIME types
<remove fileExtension=".eot" />
<mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
<mimeMap fileExtension=".otf" mimeType="font/opentype" />
<mimeMap fileExtension=".woff" mimeType="application/font-woff" />
删除默认的 IIS mime 类型,.eot 该类型为 application/octet-stream,添加正确的 MIME 类型。
迁移验证
<validation validateIntegratedModeConfiguration="false" />
Domain Cookies 设置
<httpCookies httpOnlyCookies="true" requireSSL="false" domain="yourdomainstring" />
将httpOnlyCookies
设置为 true 会在所有 cookie 上设置 httpOnly 标志,这将阻止任何客户端脚本访问 cookie;帮助减轻某些 XSS 攻击。requireSSL 属性切换是否只能在 SSL 连接下发生从服务器到客户端的 cookie 交换。domain 属性允许您手动设置 cookie 的域。
高级设置
我们可以看到可以配置的几项内容,默认情况下已注释掉:
- 自定义错误页面
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
可以注释此部分,以便配置在执行请求期间/发生未处理的错误时的处理方式。具体来说,它使开发人员可以配置要显示的 html 错误页面,以代替错误堆栈跟踪。
- 服务跨域 Ajax 请求
<add name="Access-Control-Allow-Origin" value="*" />
出于安全原因,跨域 Ajax 请求被拒绝为 default,要启用它,请取消注释上面的代码。
- 从网址中删除 WWW
<rewrite>
<rules>
<rule name="Remove WWW" stopProcessing="true">
<match url="^(.*)$" />
<conditions>
<add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
</conditions>
<action type="Redirect" url="http://example.com{PATH_INFO}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
使用网页的非 www 版本将为整个域设置 cookie,从而使无 cookie 域(例如,像 cdns 这样的对静态资源(如 css,js 和图像)的快速 cdn 访问)成为不可能。
- 对静态文件启用 Cachebusting
<rewrite>
<rules>
<rule name="Cachebusting">
<match url="^(.+)\.\d+(\.(js|css|png|jpg|gif)$)" />
<action type="Rewrite" url="{R:1}{R:2}" />
</rule>
</rules>
</rewrite>
这会将所有请求路由/path/filename.20120101.ext
到/path/filename.ext
。要使用此功能,每当您更新这些资源时,只需在 HTML 源代码中的资源文件名中添加一个时间戳号(或您自己的编号版本系统)即可。
- 允许从iframe设置Cookie
<add name="P3P" value="policyref="/w3c/p3p.xml", CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"" />
要允许从 iframe 设置 cookie(仅适用于 IE),请取消注释并在 Location 指令中指定路径或正则表达式。
服务器最低配置
这是 web.config 的简单版本,创建该版本的目的是为不使用.net 的 IIS 提供样板。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<!-- GZip static file content. Overrides the server default which only compresses static files over 2700 bytes -->
<httpCompression directory="%SystemDrive%\websites\_compressed" minFileSizeForComp="1024">
<scheme dll="%Windir%\system32\inetsrv\gzip.dll" name="gzip"/>
<staticTypes>
<add enabled="true" mimeType="text/*"/>
<add enabled="true" mimeType="message/*"/>
<add enabled="true" mimeType="application/javascript"/>
<add enabled="true" mimeType="application/json"/>
<add enabled="false" mimeType="*/*"/>
</staticTypes>
</httpCompression>
<httpErrors errorMode="Custom" existingResponse="PassThrough">
<!-- Catch IIS 404 error due to paths that exist but shouldn't be served (e.g. /controllers, /global.asax) or IIS request filtering (e.g. bin, web.config, app_code, app_globalresources, app_localresources, app_webreferences, app_data, app_browsers) -->
<remove statusCode="404" subStatusCode="-1"/>
<error path="/notfound" responseMode="ExecuteURL" statusCode="404" subStatusCode="-1"/>
<remove statusCode="500" subStatusCode="-1"/>
<error path="/error" responseMode="ExecuteURL" statusCode="500" subStatusCode="-1"/>
</httpErrors>
<directoryBrowse enabled="false"/>
<validation validateIntegratedModeConfiguration="false"/>
<!-- Microsoft sets runAllManagedModulesForAllRequests to true by default
You should handle this according to need, but consider the performance hit.
Good source of reference on this matter: http://www.west-wind.com/weblog/posts/2012/Oct/25/Caveats-with-the-runAllManagedModulesForAllRequests-in-IIS-78
-->
<modules runAllManagedModulesForAllRequests="false"/>
<urlCompression doDynamicCompression="true" doStaticCompression="true"/>
<staticContent>
<!-- Remove ETAG IN IIS >= 8 ; for IIS 7/7.5 see the Rewrite rules (bigger description of why you might remove etag down there aswell)
<clientCache setEtag="false"/>
-->
<!-- Set expire headers to 30 days for static content-->
<clientCache cacheControlMaxAge="30.00:00:00" cacheControlMode="UseMaxAge"/>
<!-- use utf-8 encoding for anything served text/plain or text/html -->
<!-- in the case of .html files; if you AJAX load html files (i.e. in angular) then remove these two lines. -->
<remove fileExtension=".html"/>
<mimeMap fileExtension=".html" mimeType="text/html; charset=UTF-8"/>
<remove fileExtension=".css"/>
<mimeMap fileExtension=".css" mimeType="text/css"/>
<remove fileExtension=".js"/>
<mimeMap fileExtension=".js" mimeType="text/javascript"/>
<remove fileExtension=".mjs"/>
<mimeMap fileExtension=".mjs" mimeType="text/javascript"/>
<remove fileExtension=".json"/>
<mimeMap fileExtension=".json" mimeType="application/json"/>
<remove fileExtension=".rss"/>
<mimeMap fileExtension=".rss" mimeType="application/rss+xml; charset=UTF-8"/>
<remove fileExtension=".xml"/>
<mimeMap fileExtension=".xml" mimeType="application/xml; charset=UTF-8"/>
<!-- HTML5 Audio/Video mime types-->
<remove fileExtension=".mp3"/>
<mimeMap fileExtension=".mp3" mimeType="audio/mpeg"/>
<remove fileExtension=".mp4"/>
<mimeMap fileExtension=".mp4" mimeType="video/mp4"/>
<remove fileExtension=".ogg"/>
<mimeMap fileExtension=".ogg" mimeType="audio/ogg"/>
<remove fileExtension=".ogv"/>
<mimeMap fileExtension=".ogv" mimeType="video/ogg"/>
<remove fileExtension=".webm"/>
<mimeMap fileExtension=".webm" mimeType="video/webm"/>
<!-- Proper svg serving. Required for svg webfonts on iPad -->
<remove fileExtension=".svg"/>
<mimeMap fileExtension=".svg" mimeType="image/svg+xml"/>
<remove fileExtension=".svgz"/>
<mimeMap fileExtension=".svgz" mimeType="image/svg+xml"/>
<!-- HTML4 Web font mime types -->
<!-- Remove default IIS mime type for .eot which is application/octet-stream -->
<remove fileExtension=".eot"/>
<mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject"/>
<remove fileExtension=".ttf"/>
<mimeMap fileExtension=".ttf" mimeType="application/x-font-ttf"/>
<remove fileExtension=".ttc"/>
<mimeMap fileExtension=".ttc" mimeType="application/x-font-ttf"/>
<remove fileExtension=".otf"/>
<mimeMap fileExtension=".otf" mimeType="font/opentype"/>
<remove fileExtension=".woff"/>
<mimeMap fileExtension=".woff" mimeType="application/font-woff"/>
<remove fileExtension=".woff2"/>
<mimeMap fileExtension=".woff2" mimeType="font/woff2"/>
<remove fileExtension=".crx"/>
<mimeMap fileExtension=".crx" mimeType="application/x-chrome-extension"/>
<remove fileExtension=".xpi"/>
<mimeMap fileExtension=".xpi" mimeType="application/x-xpinstall"/>
<remove fileExtension=".safariextz"/>
<mimeMap fileExtension=".safariextz" mimeType="application/octet-stream"/>
<!-- Flash Video mime types-->
<remove fileExtension=".flv"/>
<mimeMap fileExtension=".flv" mimeType="video/x-flv"/>
<remove fileExtension=".f4v"/>
<mimeMap fileExtension=".f4v" mimeType="video/mp4"/>
<!-- Assorted types -->
<remove fileExtension=".ico"/>
<mimeMap fileExtension=".ico" mimeType="image/x-icon"/>
<remove fileExtension=".webp"/>
<mimeMap fileExtension=".webp" mimeType="image/webp"/>
<remove fileExtension=".htc"/>
<mimeMap fileExtension=".htc" mimeType="text/x-component"/>
<remove fileExtension=".vcf"/>
<mimeMap fileExtension=".vcf" mimeType="text/x-vcard"/>
<remove fileExtension=".torrent"/>
<mimeMap fileExtension=".torrent" mimeType="application/x-bittorrent"/>
<remove fileExtension=".cur"/>
<mimeMap fileExtension=".cur" mimeType="image/x-icon"/>
<remove fileExtension=".webapp"/>
<mimeMap fileExtension=".webapp" mimeType="application/x-web-app-manifest+json; charset=UTF-8"/>
</staticContent>
<httpProtocol>
<customHeaders>
<!--#### SECURITY Related Headers ###
More information: https://www.owasp.org/index.php/List_of_useful_HTTP_headers
-->
<!--
# Access-Control-Allow-Origin
The 'Access Control Allow Origin' HTTP header is used to control which
sites are allowed to bypass same origin policies and send cross-origin requests.
Secure configuration: Either do not set this header, or return the 'Access-Control-Allow-Origin'
header restricting it to only a trusted set of sites.
http://enable-cors.org/
<remove name="Access-Control-Allow-Origin" /><add name="Access-Control-Allow-Origin" value="*" />-->
<!--
# Cache-Control
The 'Cache-Control' response header controls how pages can be cached
either by proxies or the users browser.
This response header can provide enhanced privacy by not caching
sensitive pages in the users browser cache.
<remove name="Cache-Control" /><add name="Cache-Control" value="no-store, no-cache"/>-->
<!--
# Strict-Transport-Security
The HTTP Strict Transport Security header is used to control
if the browser is allowed to only access a site over a secure connection
and how long to remember the server response for, forcing continued usage.
Note* Currently a draft standard which only Firefox and Chrome support. But is supported by sites like PayPal.
<remove name="Strict-Transport-Security" /><add name="Strict-Transport-Security" value="max-age=15768000"/>-->
<!--
# X-Frame-Options
The X-Frame-Options header indicates whether a browser should be allowed
to render a page within a frame or iframe.
The valid options are DENY (deny allowing the page to exist in a frame)
or SAMEORIGIN (allow framing but only from the originating host)
Without this option set the site is at a higher risk of click-jacking.
<remove name="X-Frame-Options" /><add name="X-Frame-Options" value="SAMEORIGIN" />-->
<!--
# X-XSS-Protection
The X-XSS-Protection header is used by Internet Explorer version 8+
The header instructs IE to enable its inbuilt anti-cross-site scripting filter.
If enabled, without 'mode=block', there is an increased risk that
otherwise non-exploitable cross-site scripting vulnerabilities may potentially become exploitable
<remove name="X-XSS-Protection" /><add name="X-XSS-Protection" value="1; mode=block"/>-->
<!--
# MIME type sniffing security protection
Enabled by default as there are very few edge cases where you wouldn't want this enabled.
Theres additional reading below; but the tldr, it reduces the ability of the browser (mostly IE)
being tricked into facilitating driveby attacks.
http://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx
http://blogs.msdn.com/b/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
-->
<remove name="X-Content-Type-Options"/>
<add name="X-Content-Type-Options" value="nosniff"/>
<!-- A little extra security (by obscurity), removings fun but adding your own is better -->
<remove name="X-Powered-By"/>
<add name="X-Powered-By" value="My Little Pony"/>
<!--
With Content Security Policy (CSP) enabled (and a browser that supports it (http://caniuse.com/#feat=contentsecuritypolicy),
you can tell the browser that it can only download content from the domains you explicitly allow
CSP can be quite difficult to configure, and cause real issues if you get it wrong
There is website that helps you generate a policy here http://cspisawesome.com/
<remove name="Content-Security-Policy" /><add name="Content-Security-Policy" "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' https://www.google-analytics.com;" />-->
<!--//#### SECURITY Related Headers ###-->
<!--
Allow cookies to be set from iframes (for IE only)
If needed, uncomment and specify a path or regex in the Location directive
<remove name="P3P" /><add name="P3P" value="policyref="/w3c/p3p.xml", CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"" />-->
</customHeaders>
</httpProtocol>
<!--
<rewrite>
<rules>
Remove/force the WWW from the URL.
Requires IIS Rewrite module http://learn.iis.net/page.aspx/460/using-the-url-rewrite-module/
Configuration lifted from http://nayyeri.net/remove-www-prefix-from-urls-with-url-rewrite-module-for-iis-7-0
NOTE* You need to install the IIS URL Rewriting extension (Install via the Web Platform Installer)
http://www.microsoft.com/web/downloads/platform.aspx
** Important Note
using a non-www version of a webpage will set cookies for the whole domain making cookieless domains
(eg. fast cdn-like access of static resources like css, js and images) impossible.
# IMPORTANT: THERE ARE TWO RULES LISTED. NEVER USE BOTH RULES AT THE SAME TIME!
<rule name="Remove WWW" stopProcessing="true">
<match url="^(.*)$" />
<conditions>
<add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
</conditions>
<action type="Redirect" url="http://example.com{PATH_INFO}" redirectType="Permanent" />
</rule>
<rule name="Force WWW" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{HTTP_HOST}" pattern="^example.com$" />
</conditions>
<action type="Redirect" url="http://www.example.com/{R:0}" redirectType="Permanent" />
</rule>
-->
<!--
### Built-in filename-based cache busting
In a managed language such as .net you should really be using the internal bundler for css + js
or getCassette or similar.
If you're not using the build script to manage your filename version revving,
you might want to consider enabling this, which will route requests for
/css/style.20110203.css to /css/style.css
To understand why this is important and a better idea than all.css?v1231,
read: http://madskristensen.net/post/cache-busting-in-aspnet
<rewrite>
<rules>
<rule name="Cachebusting">
<match url="^(.+)\.\d+(\.(js|css|png|jpg|gif)$)" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
</conditions>
<action type="Rewrite" url="{R:1}{R:2}" />
</rule>
</rules>
</rewrite>
-->
<!--
</rules>
### ETAG Removal (for IIS < 8)
E-Tags are actually quite useful in cache management especially if you have a front-end caching server
such as Varnish. http://en.wikipedia.org/wiki/HTTP_ETag / http://developer.yahoo.com/performance/rules.html#etags
But in load balancing and simply most cases ETags are mishandled in IIS; and it can be advantageous to remove them.
# removed as in https://stackoverflow.com/questions/7947420/iis-7-5-remove-etag-headers-from-response
<outboundRules>
<rule name="Remove ETag">
<match serverVariable="RESPONSE_ETag" pattern=".+" />
<action type="Rewrite" value="" />
</rule>
</outboundRules>
</rewrite>-->
<!-- Deny TRACE HTTP verb - more information: https://www.owasp.org/index.php/Test_HTTP_Methods_(OTG-CONFIG-006) -->
<security>
<requestFiltering>
<verbs>
<add verb="TRACE" allowed="false" />
</verbs>
</requestFiltering>
</security>
</system.webServer>
</configuration>
其他服务器配置样本
「Apache」
「IIS」
「Lighttpd」
「Nginx」