且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

IIS url重写|如何删除目录和扩展名?

更新时间:2023-02-23 19:52:23

我不确定我是否完全理解你的需求,但这里的东西至少是接近的。它删除了第一个文件夹和文件扩展名(所以 examplesite.com/folder/about.cshtml 变为 examplesite.com/about examplesite.com/folder/help/about.cshtml 变为 examplesite.com/help/about )。如果您要删除所有文件夹,只需删除

I'm not certain I entirely understand your needs, but here's something that's at least close. It strips out the first folder and file extension (so examplesite.com/folder/about.cshtml becomes examplesite.com/about and examplesite.com/folder/help/about.cshtml becomes examplesite.com/help/about). If you wanted to strip all folders then just remove the ?.

<rule name="Remove Directory and Extension">
    <match url="^(.*?)/(.*)\.cshtml$" />
    <action type="Rewrite" url="{R:2}" />
</rule>

更新:

好的,我认为您想要的是两个规则的组合:

Ok, I think what you want is a combination of two rules then:

<rules>
  <rule name="Redirect requests to friendly URLs">
    <match url="^(.*?)/(.*)\.cshtml$" />
    <action type="Redirect" url="{R:2}" />
  </rule>
  <rule name="Rewrite friendly URLs to phsyical paths">
    <match url="^(.*)$" />
    <action type="Rewrite" url="folder/{R:0}.cshtml" />
  </rule>
</rules>

第一条规则确保所有请求都是友好的URL。第二个获取友好URL并将其重写到您的物理路径,其中物理路径为文件夹/ [FRIENDLY_PATH] .cshtml

The first rule makes sure that all requests are to friendly URLs. The second takes the friendly URL and rewrites it to your physical path, where the physical path is folder/[FRIENDLY_PATH].cshtml.