In IIS URL Rewrite 2.0, why does HTTP_HOST include the port number?

Mike picture Mike · Oct 8, 2013 · Viewed 9k times · Source

I am trying to use IIS URL Rewrite 2.0 with IIS 8.5 on Windows 8.1. According to Accessing URL Parts from a Rewrite Rule,

For an HTTP URL in this form: http(s)://<host>:<port>/<path>?<querystring>

• The <path> is matched against the pattern of the rule.
• The <querystring> is available in the server variable called QUERY_STRING and can be accessed by using a condition within a rule.
• The <host> is available in the server variable HTTP_HOST and can be accessed by using a condition within a rule.
• The <port> is available in the server variable SERVER_PORT and can be accessed by using a condition within a rule.
• Server variables SERVER_PORT_SECURE and HTTPS can be used to determine if a secure connection was used. These server variables can be accessed by using a condition within a rule.
• The server variable REQUEST_URI can be used to access the entire requested URL path, including the query string.

To test that, here is the rule I used:

<rule name="Test" stopProcessing="true">
  <action type="Redirect" url="http://localhost/?{HTTP_HOST}" redirectType="Temporary" />
</rule>

Then I used the Composer tab in Fiddler to create the following request:

http://localhost.localdomain:65352/

to which IIS responded

HTTP/1.1 307 Moved Temporarily
Location: http://localhost/?localhost.localdomain:65352

From this we can see that the port number is included in the HTTP_HOST variable, contrary to the documentation referenced above. This adds some complexity to my matching rules because I must then account for the optional presence of a port number. How do I just get the hostname without the port number?

Answer

Billy Jo picture Billy Jo · May 19, 2015

Unfortunately, I can't tell you why it happens; but I can tell you that using {SERVER_NAME} instead of {HTTP_HOST} fixed the issue for me.

See: https://serverfault.com/a/418530/3495