簡體   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