简体   繁体   中英

URL Rewrite on IIS: HTTP to HTTPS rule to also include non-www to www redirect

How would I modify this rule to include non-www to www redirect?

    <rule name="Force Https" stopProcessing="true">
      <match url="healthcheck.html" negate="true" />
      <conditions>
        <add input="{HTTP_X_FORWARDED_PROTO}" pattern="https" negate="true" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
    </rule>

Is there a better way to force HTTPS sitewide? I am using ASP.NET MVC 5 on IIS 8.5

I think you just need to add another rule where it checks if the HTTP_HOST variable just contains your host without the www. prefix, and redirect if so:

<!-- You first rule. Note stopProcessing is now false. -->
<rule name="Force Https" stopProcessing="false">
  <match url="healthcheck.html" negate="true" />
  <conditions>
    <add input="{HTTP_X_FORWARDED_PROTO}" pattern="https" negate="true" />
  </conditions>
  <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
</rule>

<!-- Additional rule. -->
<rule name="Force WWW" stopProcessing="true">
  <match url="healthcheck.html" negate="true" />
  <conditions>
    <add input="{HTTP_HOST}" pattern="^yourdomain\.com"/>
  </conditions>
  <action type="Redirect" redirectType="Permanent" url="https://www.{HTTP_HOST}{REQUEST_URI}" />
</rule>

Just change yourdomain.com above to your actual host domain name.

To answer your other question, I think URL redirect (through URL Rewrite) is the simplest way to force HTTPS without returning a 403 to your users who still try to access your site via HTTP.

UPDATE

In response to your comment regarding the double 301, you could try this single rule. I do not have my laptop at home to verify, but I think this will work:

<!-- This rule will capture any http request regardless of the 'www.' prefix in the URL -->
<rule name="Force Https" stopProcessing="true"> 
  <match url="healthcheck.html" negate="true" />
  <conditions>
    <add input="{HTTP_X_FORWARDED_PROTO}" pattern="^http$" />
  </conditions>
  <action type="Redirect" url="https://www.yourdomain.com{REQUEST_URI}" redirectType="Permanent" />
</rule>
<!-- This rule will capture https request that does not have the 'www.' prefix in the URL -->
<rule name="Force WWW Prefix" stopProcessing="true">
  <match url="healthcheck.html" negate="true" />
  <conditions logicalGrouping="MatchAll">
    <add input="{HTTP_X_FORWARDED_PROTO}" pattern="https" />
    <add input="{HTTP_HOST}" pattern="^yourdomain\.com$"/>
  </conditions>
  <action type="Redirect" url="https://www.yourdomain.com{REQUEST_URI}" redirectType="Permanent" />
</rule>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM