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

如何让Python http.server默认展示指定非index.html文件?

如何让Python 3的http.server默认展示指定文件而非index.html?

好问题!Python自带的http.server默认只会优先加载index.html、index.htm这类标准索引文件,要让它默认展示你指定的文件(比如index1.html),有两种简单可行的方法,我帮你拆解一下:

方法1:自定义一个简单的服务器脚本(推荐,灵活可控)

这是最靠谱的方式,只需要几行代码就能自定义默认索引文件:

  1. 在你的网页根目录下创建一个文件,比如custom_server.py,把下面的代码粘进去:
from http.server import HTTPServer, SimpleHTTPRequestHandler

class CustomHandler(SimpleHTTPRequestHandler):
    # 按优先级排列你想默认加载的文件,第一个存在的会被优先展示
    index_files = ["index1.html", "index2.html", "index.html"]

if __name__ == "__main__":
    # 端口可以自己改,这里用默认的8000
    server_address = ("", 8000)
    httpd = HTTPServer(server_address, CustomHandler)
    print(f"服务器已启动:http://localhost:8000,默认优先展示{CustomHandler.index_files[0]}")
    httpd.serve_forever()
  1. 然后在命令行里运行这个脚本就行:
python custom_server.py

这样访问localhost:8000时,服务器会先找index1.html,如果找不到再依次找index2.html、index.html,完全符合你的需求,而且不需要修改任何现有网页文件。

方法2:临时重定向(适合快速测试,不用写脚本)

如果只是临时想让默认页跳转到指定文件,不用写Python脚本也能搞定:

在你的网页根目录下创建一个临时的index.html文件(如果已经有了可以先备份一下),内容只需要一行重定向代码:

<meta http-equiv="refresh" content="0; url=index1.html">

然后正常启动默认服务器:

python -m http.server

这样访问localhost:8000时,浏览器会自动跳转到index1.html。要是之后想切换默认展示index2.html,只需要修改这个重定向文件里的URL就行。

小提示:如果之后不想用重定向了,记得把原来的index.html恢复回来哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:49:49