Web.config URL Rewrites - HTTPS and Non-WWW

烈酒焚心 提交于 2019-12-13 14:09:56

问题


I need to have both https and non-www rewrites, while also NOT HARDCODING the domain, since we have numerous servers. This needs to be in the web.config, not in IIS.

I've read numerous articles:

  • http://www.iis.net/learn/extensions/url-rewrite-module/url-rewrite-module-configuration-reference
  • http://madskristensen.net/post/url-rewrite-and-the-www-subdomain
  • how to set asp.net web.config rewrite http to https and www to non-www

The https rewrite works, the non-www does not.

    <rule name="Redirect to HTTPS" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTPS}" pattern="^OFF$" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
    </rule>
    <rule name="Remove WWW" patternSyntax="Wildcard" stopProcessing="true">
      <match url="*" />
      <conditions>
        <!--<add input="{CACHE_URL}" pattern="*://www.*" />-->
        <!--<add input="{HTTP_HOST}" pattern="*://www.*" />-->
        <add input="{HTTP_HOST}" pattern="^.*www.*" />
      </conditions>
      <action type="Redirect" url="https://{SERVER_NAME}/{R:1}" redirectType="Permanent" />
      // i've also tried
      // url="{C:2}/{R:1}"
      // url="{C:1}/{C:2}"
    </rule>

I tested the regex for ^.*www.* on a regex tester and it was matching www.testing.com but not testing.com - so I would assume the pattern would catch it.

I need the URLs to redirect from:

  • testing.com ---> https://testing.com
  • www.testing.com ---> https://testing.com
  • www.testing.com/xyz/ ---> https://testing.com/xyz/

回答1:


Was my own issue - there was no DNS for the www, therefore the redirect wouldn't resolve on it's own.

Code used:

    <rule name="Redirect to HTTPS" stopProcessing="true">
      <match url="(.*)"/>
      <conditions>
        <add input="{HTTPS}" pattern="^OFF$"/>
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent"/>
    </rule>
    <rule name="Remove WWW" patternSyntax="Wildcard" stopProcessing="true">
      <match url="*" />
      <conditions>
        <add input="{CACHE_URL}" pattern="*://www.*" />
      </conditions>
      <action type="Redirect" url="{C:1}://{C:2}" redirectType="Permanent" />
    </rule>



回答2:


Add a "Canonical domain name" rule.

The soulution Rob found works fine as well. Mine seems to be a bit easier IMHO.



来源:https://stackoverflow.com/questions/39511871/web-config-url-rewrites-https-and-non-www

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!