GregoryBrad
GregoryBrad

Reputation: 1175

Change Host Header with IIS URLRewrite

I have requests coming to my webserver at

http://www.example.com/blog

I want to Rewrite that to another server listening on

http://blog.example.com

Here is my rewrite rule:

<rule name="blogredirect1" stopProcessing="true">
          <match url="^blog(.*)" />
          <action type="Rewrite" url="http://blog.example.com{R:1}"  />
</rule>

What ends up happening is the rewrite sends the request to the second servers IP at blog.mysite.com but the request header's host is still www.mysite.com.

How do I make sure that the redirected request HOST is set to blog.mysite.com (which is set in the redirect rule)

Upvotes: 1

Views: 7605

Answers (1)

Jokies Ding
Jokies Ding

Reputation: 3494

May I know how did you check the HOST header?

It is recommended to check {HTTP_HOST} variable instead of view the HTTP header directly. Because if you view the request header, you will always see www.mysite.com.

You could fetch {HTTP_HOST} request variable from backend server blog.mysite.com.

However,If you means page in blog.mysite.com also displayed {HTTP_HOST} as www.mysite.com.Then please check whether you have set system.webServer/proxy/preserveHostHeader to true?

By the way, IIS support to rewrite HTTP_HOST manually, you could modify your rule like this:

               <rule name="blogredirect1" stopProcessing="true">
          <match url="^blog(.*)" />
          <action type="Rewrite" url="http://blog.example.com{R:1}" />
                    <serverVariables>
                        <set name="HTTP_HOST" value="blog.example.com" />
                    </serverVariables>
</rule>

Please remember to Allow Server Variable{HTTP_HOST} in URL rewrite.

https://learn.microsoft.com/en-us/iis/extensions/url-rewrite-module/setting-http-request-headers-and-iis-server-variables

You could also set this in applicationhost.config <location path="sitename"> section.

 <location path="Default Web Site">
        <system.webServer>
            <rewrite>
                <allowedServerVariables>
                    <add name="HTTP_HOST" />
                </allowedServerVariables>
            </rewrite>
        </system.webServer>
    </location>

Upvotes: 3

Related Questions