这些是我开始每个项目时所遵循的标准重写规则。我对所有页面仅使用干净的 URL(示例第一条规则适用于 www.example.com/about,第二条规则适用于 www.example.com/product/123)
<rewrite>
<rules>
<rule name="Rewrite default to aspx" stopProcessing="true">
<match url="^$" ignoreCase="false" />
<action type="Rewrite" url="default.aspx" />
</rule>
<rule name="Rewrite page to aspx" stopProcessing="true">
<match url="^([a-z0-9/]+)$" ignoreCase="false" />
<action type="Rewrite" url="{R:1}.aspx" />
</rule>
</rules>
</rewrite>
我需要解析出 ID 的页面(仅此案例编号)并将其添加到查询字符串中,我在前面添加了类似的规则:
<rule name="Rewrite Product ID" stopProcessing="true">
<match url="^product/([0-9]+)$" ignoreCase="false"/>
<action type="Rewrite" url="product.aspx?id={R:1}"/>
</rule>
如果要在 URL 中使用小写和大写字母,请设置ignoreCase =“true”
编辑回答你的第二个问题加上奖金
此规则会将 aspx 页面重定向到干净的 URL:
<rule name="Redirect to clean URL" stopProcessing="true">
<match url="^([a-z0-9/]+).aspx$" ignoreCase="true"/>
<action type="Redirect" url="{R:1}"/>
</rule>
将 url="{R:1}" 替换为 url="{ToLower:{R:1}}" 将 URL 更改为小写。请参阅下文,了解您为什么要这样做。
更新表单操作也是一个好主意,这样回发就不会返回到丑陋的 URL。使用 IIS 7.5 或更高版本这应该可以工作:
if (!String.IsNullOrEmpty(Request.RawUrl))
form1.Action = Request.RawUrl;
或对于 IIS 7:
if (!String.IsNullOrEmpty(Context.Request.ServerVariables["HTTP_X_ORIGINAL_URL"]))
form1.Action = Context.Request.ServerVariables["HTTP_X_ORIGINAL_URL"];
还有一件事要记住...最好将所有 URL 保持小写。在 URL 中混合小写/大写字符会给 SEO/Google 带来重复内容问题。例如,website.com/About 和 website.com/about 将加载同一页面,但 Google 会将它们索引为两个单独的页面。