在虛擬主機或無法存取 IIS 設定的環境下,可透過 URLRewriter.dll 在應用程式層級實現 URL 重寫,將 show.aspx?id=12345 映射為 12345.html 或無副檔名的靜態風格網址。
URLRewriter.dll。bin 目錄並加入參考。<configuration>
<configSections>
<section name="RewriterConfig"
type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />
</configSections>
...
<system.web>
<httpHandlers>
<add verb="*" path="*.html"
type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
<add verb="*" path="*"
type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
</httpHandlers>
</system.web>
順序很重要:*.html 必須在 * 之前,否則通用規則會優先攔截。
<RewriterConfig>
<Rules>
<RewriterRule>
<LookFor>~/(.+)\.html</LookFor>
<SendTo>~/Shownews.aspx?ShowID=$1</SendTo>
</RewriterRule>
<RewriterRule>
<LookFor>~/(.+)</LookFor>
<SendTo>~/blog.aspx?UserName=$1</SendTo>
</RewriterRule>
</Rules>
</RewriterConfig>
~/(.+)\.html → 對應 Shownews.aspx?ShowID=...~/(.+) → 對應 blog.aspx?UserName=... (無副檔名)$1, $2...<a href="news_<%=newsid%>.html" target="_blank">新聞標題</a>
若重寫失效,需在 IIS「處理常式對應」加入萬用字元對應:
C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll (依 .NET 版本調整)。<ReWriterUrls>
<rule>
<old>(.*)/TestUrlRe/file(.*)/(.*).html</old>
<new>../WebForm1.aspx?id=$2&type=$3</new>
</rule>
</ReWriterUrls>