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

在IIS上部署Next.js应用时无法加载.css与.js静态文件

解决IIS部署Next.js后静态资源(CSS/JS)无法加载的问题

你遇到的静态资源加载失败问题,核心是web.config里的静态资源重写规则配置错误,导致请求无法正确映射到.next/static目录下的实际文件。下面是具体的修复步骤:

1. 修正静态资源重写规则

你原来的StaticContent规则缺少URL匹配条件,会导致所有请求都被错误重写。替换成以下规则,它会精准匹配/_next/static/开头的静态资源请求:

<rule name="StaticContent" stopProcessing="true">
  <match url="^/_next/static/(.*)" />
  <action type="Rewrite" url=".next/static/{R:1}" />
</rule>

{R:1}会捕获请求URL中/_next/static/之后的路径部分,保证请求能对应到.next/static目录下的具体文件。

2. 确保规则顺序正确

把修正后的StaticContent规则放在DynamicContent规则之前,因为IIS重写规则是按从上到下的顺序执行的,先处理静态资源请求,再处理动态路由请求。

3. 完整的修改后web.config

替换后的完整配置文件如下:

<configuration>
  <system.webServer>
      <httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="*" />
          <add name="Access-Control-Allow-Methods" value="*" />
          <add name="Access-Control-Allow-Headers" value="*" />
        </customHeaders>
      </httpProtocol>

    <webSocket enabled="false" />

    <handlers>
      <add name="iisnode" path="server.js" verb="*" modules="iisnode"/>
    </handlers>

    <rewrite>
      <rules>
        <rule name="NodeInspector" patternSyntax="ECMAScript" stopProcessing="true">
          <match url="^server.js\/debug[\/]?" />
        </rule>

        <!-- 修正后的静态资源规则 -->
        <rule name="StaticContent" stopProcessing="true">
          <match url="^/_next/static/(.*)" />
          <action type="Rewrite" url=".next/static/{R:1}" />
        </rule>

        <rule name="DynamicContent">
          <conditions>
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="True"/>
          </conditions>
          <action type="Rewrite" url="server.js"/>
        </rule>
      </rules>
    </rewrite>
    
    <security>
      <requestFiltering>
        <hiddenSegments>
          <add segment="node_modules"/>
        </hiddenSegments>
      </requestFiltering>
    </security>

    <httpErrors existingResponse="PassThrough" />

    <iisnode 
        watchedFiles="web.config;*.js;node_modules\*;"
        node_env="production"
        />
  </system.webServer>
</configuration>

4. 额外检查项

  • 部署前必须运行npm run build生成生产环境的.next目录,不要直接部署开发环境代码
  • 确认IIS已安装iisnode模块,且站点应用池设置为No Managed Code
  • 检查站点目录权限,给IIS_IUSRS或应用池身份添加读取权限,确保IIS能访问.next目录

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 04:25:02