You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

配置IIS的web.config:除物理文件/目录外将请求路由至index.php

解决IIS下替代.htaccess实现URL路由到index.php的问题

刚好踩过这个坑!IIS不支持Apache的.htaccess文件,所以得用web.config来配置URL重写,实现你要的把所有请求路由到index.php的伪静态效果(比如把site.com/something映射成site.com/index.php?/something)。

下面是完整可用的web.config配置,包含你提到的移除末尾斜杠规则,加上核心路由逻辑:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <!-- 移除URL末尾的斜杠(避免重复内容) -->
        <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>
        
        <!-- 核心规则:把所有非文件/目录的请求路由到index.php -->
        <rule name="Rewrite to index.php" stopProcessing="true">
          <match url="^(.*)$" ignoreCase="false" />
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          </conditions>
          <action type="Rewrite" url="index.php?/{R:1}" appendQueryString="true" />
        </rule>
      </rules>
    </rewrite>

    <!-- 可选:确保PHP脚本能被IIS正确解析(根据你的PHP安装路径调整) -->
    <handlers>
      <add name="PHP_via_FastCGI" path="*.php" verb="*" modules="FastCgiModule" 
           scriptProcessor="C:\Program Files\PHP\v8.2\php-cgi.exe" 
           resourceType="Either" requireAccess="Script" />
    </handlers>
  </system.webServer>
</configuration>

规则细节说明:

  • 移除末尾斜杠:这个规则会把site.com/something/永久重定向到site.com/something,同时跳过真实存在的文件夹和文件,避免影响正常访问。
  • 路由到index.php:所有不是真实文件或文件夹的请求,都会被悄悄重写为index.php?/xxx的格式,浏览器地址栏不会变化,完美实现伪静态。而且appendQueryString="true"会保留原有的查询参数,比如site.com/something?foo=bar会正确传递参数到index.php

必须做的前置操作:

  1. 确认你的IIS服务器安装了URL重写模块——打开IIS管理器,看“模块”里有没有RewriteModule,没有的话去微软官网下载安装(是免费的)。
  2. web.config放到网站根目录,和你的index.php同级。
  3. 如果你的PHP路径不是示例里的C:\Program Files\PHP\v8.2\php-cgi.exe,记得修改handlers里的scriptProcessor路径,改成你服务器上的实际路径。

测试的时候直接访问site.com/任意路径,然后在index.php里用var_dump($_GET)或者var_dump($_SERVER['REQUEST_URI'])就能看到路由过来的参数了,没问题的话就生效啦!

内容的提问来源于stack exchange,提问作者hretic

火山引擎 最新活动