我用百度的文心一言写了一段域名跳转代码

我今天用百度一言写了一段代码,帮我省下了一笔开支。下面来说一下过程,我的本意是通过设置web.config文件,在IIS环境中同时实现不带wwww的主域名跳转到带wwww的根域名,以及将带http的主域名跳转到带https的根域名。然后百度一言告诉我,你可以使用IIS的URL重写模块来配置两个重写规则。以下是web.config文件的示例内容,它包含了这两个规则:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="UTF-8"?>  
<configuration>
<system.webServer>
<rewrite>
<rules>
<!-- Rule to redirect non-www to www -->
<rule name="Redirect non-www to www" stopProcessing="true">
<match url="^(.*)$" />
<conditions>
<add input="{HTTP_HOST}" pattern="^yourdomain\.com$" />
</conditions>
<action type="Redirect" url="https://www.yourdomain.com/{R:1}" redirectType="Permanent" />
</rule>
<!-- Rule to redirect HTTP to HTTPS -->
<rule name="Redirect HTTP to HTTPS" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="^OFF$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>

百度一言给出的代码解释:

  1. 第一个规则:Redirect non-www to www
    1. name:规则的名称,用于标识这个规则。
    2. stopProcessing:如果设置为true,则处理完这个规则后不再继续处理其他规则。
    3. <match>:定义要匹配的URL模式。这里使用^(.*)$来匹配所有请求的路径和查询字符串。
    4. <conditions>:定义规则应用的条件。这里我们检查{HTTP_HOST}(即请求的主机头)是否匹配^yourdomain\.com$(不带www的域名)。请将yourdomain.com替换为你的实际域名。
    5. <action>:定义当规则匹配时要执行的操作。这里我们使用Redirect类型,将请求重定向到https://www.yourdomain.com/{R:1}(其中{R:1}是匹配到的URL的剩余部分)。redirectType设置为Permanent(301重定向),表示这是一个永久性的重定向。
  2. 第二个规则:Redirect HTTP to HTTPS
    1. name:规则的名称,用于标识这个规则。
    2. stopProcessing:同样设置为true
    3. <match>:匹配所有请求的URL路径和查询字符串。
    4. <conditions>:检查{HTTPS}服务器变量是否等于OFF,这表示请求是通过HTTP而不是HTTPS发送的。
    5. <action>:将请求重定向到https://{HTTP_HOST}/{R:1},其中{HTTP_HOST}是请求的主机头(即域名),{R:1}是匹配到的URL的剩余部分。redirectType也设置为Permanent

百度一言提示的注意事项:

  1. 请确保将yourdomain.com替换为你的实际域名。
  2. 如果你的网站有多个绑定的域名或子域名,并且你只想对特定的域名应用这些重定向,你可能需要调整<conditions>部分以更精确地匹配请求的主机头。
  3. 在将web.config文件部署到生产环境之前,建议在测试环境中验证重定向是否按预期工作。
  4. 如果你的网站已经使用了SSL证书,并且IIS已经配置了HTTPS绑定,这些规则才能正确地将HTTP请求重定向到HTTPS。
  5. 如果你的网站在负载均衡器或反向代理后面运行,可能还需要配置这些组件以正确处理重定向。

调整域名

把里面的域名换成我自己的域名,保存上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="UTF-8"?>  
<configuration>
<system.webServer>
<rewrite>
<rules>
<!-- Rule to redirect non-www to www -->
<rule name="Redirect non-www to www" stopProcessing="true">
<match url="^(.*)$" />
<conditions>
<add input="{HTTP_HOST}" pattern="^laoboke\.cn$" />
</conditions>
<action type="Redirect" url="https://www.laoliublog.com/{R:1}" redirectType="Permanent" />
</rule>
<!-- Rule to redirect HTTP to HTTPS -->
<rule name="Redirect HTTP to HTTPS" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="^OFF$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>

竟然真的实现了,很不错的代码,分享给大家。