asp.net - 如何重写 url 以删除 aspx 扩展名并重定向结尾的斜杠?

标签 asp.net iis redirect url-rewriting seo

我想删除干净 url 的 aspx 扩展名,并在使用尾部斜杠时重定向。

在我的 web.config 文件中:

<!-- Rewrite, adding extension -->
<rule name="add aspx">
  <match url="(.*)" />
  <conditions logicalGrouping="MatchAll">
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
    <add input="{REQUEST_FILENAME}" negate="true" pattern="\.axd$" />
  </conditions>
  <action type="Rewrite" url="{R:1}.aspx" />
</rule>
<!-- Removes trailing slash after rewrite -->
<rule name="remove trailing slash after rewrite" stopProcessing="true">
  <match url="(.*)/.aspx$" />
  <conditions>
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
  </conditions>
  <action type="Redirect" redirectType="Permanent" url="{R:1}" />
</rule>

所以,基本上,如果一个人请求 url“mysite/mypage”,这将添加 aspx 扩展名并且工作正常,当一个人请求“mysite/mypage/”时,他们将被重定向到“mysite/mypage”。

我的解决方案似乎可行,但是否有更有效的方法来完成重写而不是重定向?

最佳答案

我没有意识到顺序很重要,所以我执行了以下操作:首先重定向尾部斜杠,然后重写。

<rule name="Remove trailing slash" stopProcessing="true">
  <match url="(.*)/$" />
  <conditions>
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
  </conditions>
  <action type="Redirect" redirectType="Permanent" url="{R:1}" />
</rule>
<rule name="Add aspx">
  <match url="(.*)" />
  <conditions logicalGrouping="MatchAll">
    <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
    <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
    <add input="{REQUEST_FILENAME}" negate="true" pattern="\.axd$" />
  </conditions>
  <action type="Rewrite" url="{R:1}.aspx" />
</rule>

这似乎是最好的方法,除非有人知道更好的方法。

关于asp.net - 如何重写 url 以删除 aspx 扩展名并重定向结尾的斜杠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22334456/

相关文章:

asp.net - 带有服务总线的 SignalR Azure 云服务

asp.net - 如何安全地获取正在运行的 ASP.NET 站点的域名

c# - 无法在 Jquery ajax 调用中发送大数据

asp.net - IIS 7、HttpHandler 和 HTTP 错误 500.21

regex - 重定向 .htaccess - 删除 url 的最后一部分

redirect - 银条纹。如何从www.域名重定向到域名?

javascript - 将数组从 Javascript 传递到 asp.net

css - 响应式 Bootstrap 设计导致 div 通过添加 help-block 移动

asp.net - 使用 Asp.Net 进行 CSS/JS GZip 压缩

javascript - 无法访问 javascript 中的 url