IIS web.config重定向目录以及重定向URL中文乱码问题的解决方法
介绍
由于博客删除了分类页面,并将分类与标签进行合并,因此无法从分类页面的URL访问对应的内容。
自转至HEXO以来,就一直使用分类页面(/categories/*),所以在搜索引擎中还保留着相关的条目。
为了将浏览者引导至合并后的页面(/tags/*),就开始折腾IIS的web.config。
重定向目录
由于分类页面已经合并到标签页面,所以需要将所有分类页面的链接(/categories/*)重定向到标签页面(/tags/*)。
网上很多内容都是带着匹配内容的目录进行转跳,例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <?xml version="1.0"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0"/> </system.web> <system.webServer> <rewrite> <rules> <rule name="Categories to Tags" stopProcessing="true"> <match url="^categories/.*" /> <conditions> <add input="{HTTP_HOST}" pattern="^zerokami.cn$" /> </conditions> <action type="Redirect" url="https://zerokami.cn/tags/{R:0}" redirectType="Permanent" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
|
(/categories/*)重定向至(/tags/categories/*),这显然就不是我们所需要的效果。
最后找到了一篇文章详细的讲述了如何进行目录的重定向。(IIS设置URL重写,实现页面的跳转的重定向方法_iis url转发-CSDN博客)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <?xml version="1.0"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0"/> </system.web> <system.webServer> <rewrite> <rules> <rule name="Categories to Tags" stopProcessing="true"> <match url="^categories/(.*)" /> <conditions> <add input="{HTTP_HOST}" pattern="^zerokami.cn$" /> </conditions> <action type="Redirect" url="https://zerokami.cn/tags/{R:1}" redirectType="Permanent" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
|
需要注意,在匹配url中需要保留的内容是需要用括号括起来的,否则会导致报错 The page cannot be displayed because an internal server error has occurred.
至此,分类页面的链接(/categories/*)重定向到标签页面(/tags/*)的问题就解决了。
重定向URL中含有中文导致URL乱码
虽然分类页面的链接(/categories/*)重定向到标签页面(/tags/*)的问题就解决了,但是也遇到了新的问题。
我之前的分类中是含有中文的,例如:作品。这些含有中文的URL重定向后会造成乱码,页面报错。
解决方法也是有的,可以参考URL 重写模块配置参考 | Microsoft Learn。
字符串函数
有三个字符串函数可用于更改重写规则作中的值,以及任何条件:
- ToLower - 返回转换为小写的输入字符串。
- UrlEncode - 返回转换为 URL 编码格式的输入字符串。 如果重写规则中的替换 URL 包含特殊字符(例如非 ASCII 或 URI 不安全字符),则可以使用此函数。
- UrlDecode - 解码 URL 编码的输入字符串。 此函数可用于解码条件输入,然后再将其与模式匹配。
可以使用以下语法调用这些函数:
1
| {function_name:any_string}
|
其中,“function_name”可能位于以下位置:“ToLower”、“UrlEncode”、“UrlDecode”。 “Any_string”可以是文本字符串,也可以是使用服务器变量或反向引用生成的字符串。 例如,下面是字符串函数的有效调用:
1 2 3
| {ToLower:DEFAULT.HTM} {UrlDecode:{REQUEST_URI}} {UrlEncode:{R:1}.aspx?p=[résumé]}
|
这里我们可以使用UrlEncode函数,因为它可重写规则中的替换 URL 包含特殊字符(例如非 ASCII 或 URI 不安全字符)。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <?xml version="1.0"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0"/> </system.web> <system.webServer> <rewrite> <rules> <rule name="Categories to Tags" stopProcessing="true"> <match url="^categories/(.*)" /> <conditions> <add input="{HTTP_HOST}" pattern="^zerokami.cn$" /> </conditions> <action type="Redirect" url="https://zerokami.cn/tags/{UrlEncode:{R:1}}" redirectType="Permanent" /> </rule> </rules> </rewrite> </system.webServer> </configuration>
|
至此,所有的问题也都得到了解决,下班收工!
参考