繁体   English   中英

ASP.NET MVC 5中子域路由的IIS URL重写规则

[英]IIS URL Rewrite Rules for Subdomain Routing in ASP.NET MVC 5

我有一个用ASP.NET MVC 5编写的Web应用程序,其中包含有关其用户的信息。 现在,我想为可作为我的网站的子域访问的每个用户(例如user1.example.comuser2.example.com ,...)创建一个配置文件页面。

我希望这些子域可以通过HTTP访问,而应用程序的其余部分必须要求使用HTTPS。

我在IIS上运行Web应用程序,所以我认为最好是使用URL重写规则将user1.example.com重写为example.com/Profile/Index?name=user1 ,因此Web应用程序本身不必了解正在使用的子域。 我想出了这些重写规则:

<rewrite>
  <rules>
    <clear />
    <rule name="Rewrite user subdomains into query string" stopProcessing="true">
      <match url="^(.+)" />
      <conditions>
        <add input="{HTTP_HOST}" negate="true" pattern="^www\.example\.com$" />
        <add input="{HTTP_HOST}" pattern="^([^.]+)\.example\.com$" />
      </conditions>
      <action type="Rewrite" url="/Profile/Index?name={C:1}" />
    </rule>
    <rule name="Redirect to https without www" stopProcessing="true">
      <match url="(.*)" />
      <conditions trackAllCaptures="false">
        <add input="{HTTP_HOST}" pattern="^www\.example\.com$" />
        <add input="{HTTP_HOST}" pattern="^example\.com$" />
      </conditions>
      <action type="Redirect" url="https://example.com/{R:1}" redirectType="Permanent" />
    </rule>
  </rules>
</rewrite>

不幸的是,此代码不会将user1.example.com重写为example.com/Profile/Index?name=user1 ,甚至对user1.example.com也强制实施HTTPS。

有人可以向我解释为什么以及如何解决吗?

我最终使用了以下代码:

<rewrite>
  <rules>
    <clear />
    <rule name="Rewrite url with tenant subdomain" stopProcessing="true">
      <match url="^$" /> <!-- So resources like user1.example.com/Content/css wouldn't be affested by this rewrite -->
      <conditions>
        <add input="{HTTP_HOST}" negate="true" pattern="^www\.example\.com$" />
        <add input="{HTTP_HOST}" pattern="^([^.]+)\.example\.com$" />
      </conditions>
      <action type="Rewrite" url="Profile/Index?subdomain={C:1}" />
    </rule>
    <rule name="Redirect to www.example.com" stopProcessing="true">
      <match url="(.*)"/>
      <conditions>
        <add input="{HTTP_HOST}" pattern="^example\.com$"/>
      </conditions>
      <action type="Redirect" url="https://www.example.com/{R:1}" redirectType="Permanent" />
    </rule>
    <rule name="Redirect to https" stopProcessing="true">
      <match url="(.*)" />
      <conditions>
        <add input="{HTTPS}" pattern="^OFF$" />
      </conditions>
      <action type="Redirect" url="https://www.example.com/{R:1}" redirectType="Permanent" />
    </rule>
  </rules>
</rewrite>

让我感到困惑的是,Index模板中的Url帮助器开始抛出System.Web.HttpException: Cannot use a leading .. to exit above the top directory. 由于这是我唯一需要特定租户的页面,因此我放弃了,对链接进行了硬编码,一切开始正常运行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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