• ASP.Net
  • 常用語法介紹
  • 轉址
  • import_contacts URL Rewrite:更具親和力的網址
    8727
適用範圍

親民的 URL 在商業行為上很重要,但在技術上要實現目前也已經不困難,其中的問題在於如何將外部的 URL(即親民的 URL)轉換成內部真正處理的動態 URL,畢竟不可能要求企業網站為了要做親民的 URL,而去生出來數千張或數萬張靜態網頁,而又不能自動和資料庫連線以更新內容,所以在技術領域便定義了一個新的名詞:URL Rewriting(URL 重寫)。

實用性:
重要性:

URL Rewrite

背景

URL Rewrite 是由 IIS 團隊所開發(目前版本為 2.0),在 Web 伺服器層執行 URL Rewriting 的擴充元件,透過 URL Rewrite 模組,不論是靜態或動態的網頁,都可以被轉換成親民的 URL,而且對內部而言它也不會受到外部 URL 的影響,URL Rewrite 會自動將連入要求的 URL 轉換成程式可讀的內部 URL,以讓程式可以保持正常執行。

參數說明

<rule name="Canonical Host Name" stopprocessing="true">
    <match url="(.*)">
    <conditions>
        <add input="{HTTP_HOST}" negate="true" pattern="^192.168.1.1$">
        <add input="{HTTP_HOST}" pattern="^example\.com$">
        <add input="{HTTP_HOST}" negate="true" pattern="^www\.example\.com$">
    </add></add></add></conditions>
    <action type="Redirect" url="http://www.example.com/{R:1}">
</action>
</match>
</rule>

上面的規則會把 http://www.example.com/Examples/index.html 或是 http://www.example.com/Examples/example-123.html 的網址替換成 output/Examples/index.html 或是 output/Examples/example-123.html

參數
Match URL
Requested URL Matches the pattern
Using Regular Expression
Pattern ^article/([0-9]+)/([_0-9a-z-]+)
Action
Action Type Rewrite
Rewrite URL Rewrite.aspx?id={R:1}&title={R:2}

強制轉向到HTTPS

<system.webServer>

  <rewrite>
    <rules>
      <rule name="HTTP to HTTPS redirect" stopProcessing="true">
        <match url="(.*)" />
        <conditions>
          <add input="{HTTPS}" pattern="off" ignoreCase="true" />
        </conditions>
        <action type="Redirect" redirectType="Found" 
                url="https://{HTTP_HOST}/{R:1}" />
      </rule>
    </rules>
  </rewrite>

</system.webServer>