How to add a header to an IIS rewrite redirect URL?

I am trying to prepare the site for pre-loading HSTS, and one of the requirements is that the root domain also supports HSTS. I serve the pages on www. so I need to redirect from the root domain to "www". subdomain. Since this is a static site hosted on Azure, I am trying to get everything to work with the IIS URL rewriter module.

Here is what I still have:

<configuration> <system.webServer> <rewrite> <rules> <clear /> <!-- http -> https --> <rule name="https" enabled="true"> <match url="(.*)" /> <conditions logicalGrouping="MatchAll"> <add input="{HTTPS}" pattern="off" ignoreCase="true" /> </conditions> <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" /> </rule> <!-- https://anything -> https://www.example.com --> <rule name="redirect" enabled="true"> <match url="(.*)" /> <conditions logicalGrouping="MatchAll"> <add input="{HTTPS}" pattern="on" ignoreCase="true" /> <add input="{HTTP_HOST}" pattern="^(?!www.example.com$).*$" /> </conditions> <action type="Redirect" url="https://www.example.com{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" /> </rule> </rules> <outboundRules> <rule name="hsts" enabled="true"> <match serverVariable="RESPONSE_Strict_Transport_Security" pattern=".*" /> <conditions> <add input="{HTTPS}" pattern="on" ignoreCase="true" /> </conditions> <action type="Rewrite" value="max-age=31536000; includeSubDomains; preload" /> </rule> </outboundRules> </rewrite> </system.webServer> </configuration> 

Redirecting works fine:

The problem is that outboundRules not applied when using the Redirect action (from MS docs at https://docs.microsoft.com/en-us/iis/extensions/url-rewrite-module/url-rewrite-module-configuration- reference ):

Using the redirect action implies that subsequent rules evaluated for the current URL after the redirect are not executed.

This means that the 301 response from https://example.com β†’ https://www.example.com will not have an HSTS header, as required by pre-loading HSTS.

Also note that while customHeaders ( https://docs.microsoft.com/en-us/iis/configuration/system.webserver/httpprotocol/customheaders/ ) can usually be used to add headers to any response, the HSTS specification explicitly prohibits adding the Strict-Transport-Security header to responses other than HTTPS. I was unable to determine how to use customHeaders conditionally, although this would also solve this specific problem if there was a way to do this.

So, the question is: how can I add headers (in particular, the Strict-Transport-Security header) to the 301 response generated by the redirect?

+5
source share

Source: https://habr.com/ru/post/1273183/


All Articles