Redirecting to HTTPS while keeping the specified port number

ghz 8months ago ⋅ 67 views

I am using IIS 10.0.17763 and configured HSTS to redirect HTTP to HTTPS. It works fine going from port 80 to 443, but if is specify a different port it still redirects to 443 instead of the original port.

I entered HTTP://site.mydomain.com:8080 and expected it to go to HTTPS://site.mydomain.com:8080. Instead, it went to HTTPS://site.mydomain.com without the port number.

Is there a way to do this with HSTS alone or do I need to use IIS URL Rewrite rules?

Answers

HTTP Strict Transport Security (HSTS) is a web security policy mechanism that helps to protect websites against man-in-the-middle attacks such as protocol downgrade attacks and cookie hijacking. However, HSTS does not directly handle port redirection. It only enforces that the browser should only access the site over HTTPS, but it does not control the port number.

To achieve redirection to HTTPS with the original port number included, you can indeed use IIS URL Rewrite rules. Here's how you can configure it:

  1. Open IIS Manager.
  2. Select your site.
  3. Double-click on "URL Rewrite" feature.
  4. Click on "Add Rule(s)...".
  5. Choose "Blank rule" and click "OK".
  6. Enter a name for the rule, such as "Redirect to HTTPS with original port".
  7. In the "Match URL" section:
    • Set "Requested URL" to "Matches the Pattern".
    • Set "Using" to "Regular Expressions".
    • In the "Pattern" field, enter (.*).
  8. In the "Conditions" section:
    • Click "Add...".
    • Set "Condition input" to {HTTPS}.
    • Set "Check if input string" to "Does not match the Pattern".
    • In the "Pattern" field, enter ^ON$.
    • This condition ensures that the rule only applies to non-HTTPS requests.
  9. In the "Action" section:
    • Set "Action type" to "Redirect".
    • Set "Redirect URL" to https://{HTTP_HOST}:{SERVER_PORT}{REQUEST_URI}.
    • Check "Append query string".
    • Set "Redirect type" to "Permanent (301)".
  10. Click "Apply" to save the rule.

This rule will redirect all non-HTTPS requests to HTTPS, while preserving the original port number in the URL. Make sure to test it thoroughly to ensure it works as expected in your environment.