You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IIS Rewrite模块异常:不同URL下JS加载结果不一致问题排查

问题背景

运行环境

  • Windows 11
  • IIS 10.0
  • IIS Rewrite Module 2

网站目录结构

wwwroot
    |
    +--testproject
         |--web.config
         +--public
         |    |
         |    |--index.php
         |    +--assets
         |          |
         |          +--js
         |              |
         |              |--testscript.js
         +--app…

相关文件内容

web.config

<configuration>
<system.webServer>
<rewrite>
<rules>
    <rule name="Rewrite routed access to assets javascript" stopProcessing="true">
        <match url="^(.*)(/js/[a-zA-Z0-9]*.js)$" />
        <action type="Rewrite" url="public/assets{R:2}" appendQueryString="false" logRewrittenUrl="true" />
    </rule>

    <rule name="Rewrite requested file/folder to index.php" stopProcessing="true">
        <match url="^(.*)$" ignoreCase="false" />
        <action type="Rewrite" url="public/index.php" appendQueryString="true" />
    </rule>
</rules>
</rewrite>
</system.webServer>
</configuration>

index.php

<html>
    <body>
        <h1>Testpage</h1>
        <h3>Text from javascript testscript.js</h3>
        <div id="testdiv"></div>
        <script src="js/testscript.js"></script>
    </body>
</html>

testscript.js

var e = document.getElementById("testdiv")
e.innerHTML = "Lorum ipsum...";

问题描述

访问 http://localhost/testproject/users 时加载JavaScript出现错误,而访问 http://localhost/testproject/users/23 时脚本可正常运行,请问原因是什么?


原因解析

问题根源在浏览器相对路径解析逻辑和IIS重写规则的匹配限制上:

  1. 浏览器解析相对路径的差异

    • 访问http://localhost/testproject/users时,浏览器会把users识别为当前目录下的文件,解析<script src="js/testscript.js">后,发起的请求是http://localhost/testproject/js/testscript.js。
    • 访问http://localhost/testproject/users/23时,浏览器会把users/识别为当前目录,解析后发起的请求是http://localhost/testproject/users/js/testscript.js。
  2. 重写规则的匹配限制
    第一个重写规则的正则^(.*)(/js/[a-zA-Z0-9]*.js)$要求URL路径中必须包含带前置斜杠的/js/片段:

    • 对于users/js/testscript.js这个路径,存在/js/片段,能匹配规则,被正确重写到public/assets/js/testscript.js,可以正常加载JS文件。
    • 对于js/testscript.js这个路径,js前没有斜杠,无法匹配第一个规则,会触发第二个规则被重写到public/index.php,返回的是HTML页面而非JS文件,浏览器因此报错。

内容的提问来源于stack exchange,提问作者Pjere van Vollenhove

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 21:12:40