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

如何通过IIS的httpPlatformHandler部署FastAPI并解决路径404问题

FastAPI(Python 3.7)部署IIS:移除多余路径并解决404问题

一、正确配置httpPlatformHandler

确保你的web.config中httpPlatform部分正确指向Python和Uvicorn启动命令,同时开启日志便于排查:

<configuration>
  <system.webServer>
    <handlers>
      <add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" requireAccess="Script" />
    </handlers>
    <httpPlatform processPath="C:\Python37\python.exe"
                  arguments="-m uvicorn main:app --host 127.0.0.1 --port 8000 --workers 1"
                  stdoutLogEnabled="true"
                  stdoutLogFile=".\logs\uvicorn.log"
                  startupTimeLimit="60"
                  requestTimeout="00:05:00">
      <environmentVariables>
        <environmentVariable name="PYTHONPATH" value="%SystemDrive%\Python37;%SystemDrive%\Python37\Lib\site-packages" />
      </environmentVariables>
    </httpPlatform>
  </system.webServer>
</configuration>
  • 替换processPath为你的Python 3.7实际安装路径
  • arguments中的main:app对应你的FastAPI入口文件(比如main.py中的app = FastAPI())
  • 开启stdoutLogEnabled后,检查logs目录下的日志,确认Uvicorn是否正常启动

二、配置URL Rewrite移除多余路径

要解决请求中携带的/webapis/api/fast.py多余路径问题,需要添加URL重写规则,将请求转发到本地8000端口的Uvicorn服务,并剥离多余路径:

  1. 确保IIS已安装URL Rewrite模块和Application Request Routing (ARR)(ARR用于反向代理转发)
  2. 在web.config的<system.webServer>节点下添加<rewrite>配置:
<rewrite>
  <rules>
    <rule name="Remove Extra Path and Proxy" stopProcessing="true">
      <!-- 匹配包含/webapis/api/fast.py的请求路径 -->
      <match url="^webapis/api/fast.py/(.*)" />
      <!-- 条件:确保请求不是针对静态文件 -->
      <conditions>
        <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
        <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
      </conditions>
      <!-- 重写路径:剥离多余部分,转发到Uvicorn的8000端口 -->
      <action type="Rewrite" url="http://127.0.0.1:8000/{R:1}" />
    </rule>
    <!-- 处理根路径请求(如果需要) -->
    <rule name="Root Proxy" stopProcessing="true">
      <match url="^webapis/api/fast.py$" />
      <action type="Rewrite" url="http://127.0.0.1:8000/" />
    </rule>
  </rules>
</rewrite>
  • 第一个规则匹配/webapis/api/fast.py/xxx格式的请求,将xxx部分转发到http://127.0.0.1:8000/xxx
  • 第二个规则处理直接请求/webapis/api/fast.py的情况,转发到Uvicorn的根路径
  • 确保stopProcessing="true",避免后续规则干扰

三、关键验证步骤

  1. 重启IIS站点,查看Uvicorn日志确认服务正常运行
  2. 发送测试请求GET /webapis/api/fast.py/hello/bob,检查Uvicorn日志是否收到GET /hello/bob的请求
  3. 如果仍返回404,检查:
    • ARR模块是否已启用(IIS管理器 -> 服务器节点 -> Application Request Routing Cache -> 服务器代理设置 -> 勾选"启用代理")
    • URL Rewrite规则的正则表达式是否匹配你的实际路径
    • Uvicorn是否确实监听127.0.0.1:8000,可通过curl http://127.0.0.1:8000/hello/bob直接测试Uvicorn服务

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:07:38