在CentOS/Ubuntu上托管静态HTML文件,推荐使用Nginx或Apache作为生产环境方案,但如果你需要快速简单的解决方案,以下是几种方法:
1. 使用Python的http.server(快速测试)
# Python 3
python3 -m http.server 8000
# 指定目录
python3 -m http.server 8000 --directory /path/to/html
# 允许外部访问(默认只允许localhost)
python3 -m http.server 8000 --bind 0.0.0.0
2. 使用Flask(简单灵活)
# app.py
from flask import Flask, send_from_directory
import os
app = Flask(__name__)
@app.route('/')
def serve_index():
return send_from_directory('.', 'index.html')
@app.route('/<path:path>')
def serve_static(path):
return send_from_directory('.', path)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000, debug=True)
运行:
pip install flask
python app.py
3. 生产环境推荐:Nginx
Ubuntu安装配置:
# 安装
sudo apt update
sudo apt install nginx
# 创建配置文件
sudo nano /etc/nginx/sites-available/static-site
# 配置内容
server {
listen 80;
server_name your-domain.com;
root /var/www/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
# 启用站点
sudo ln -s /etc/nginx/sites-available/static-site /etc/nginx/sites-enabled/
sudo nginx -t # 测试配置
sudo systemctl restart nginx
CentOS安装配置:
# 安装
sudo yum install epel-release
sudo yum install nginx
# 启动并设置开机自启
sudo systemctl start nginx
sudo systemctl enable nginx
# 配置文件位置:/etc/nginx/nginx.conf
4. 使用systemd服务(持久化运行)
创建Flask服务的systemd配置:
# /etc/systemd/system/static-site.service
[Unit]
Description=Static HTML Site
After=network.target
[Service]
User=www-data
WorkingDirectory=/var/www/html
ExecStart=/usr/bin/python3 /var/www/html/app.py
Restart=always
[Install]
WantedBy=multi-user.target
启用服务:
sudo systemctl daemon-reload
sudo systemctl start static-site
sudo systemctl enable static-site
5. 使用Docker(容器化部署)
# Dockerfile
FROM nginx:alpine
COPY . /usr/share/nginx/html
EXPOSE 80
运行:
docker build -t static-site .
docker run -d -p 80:80 static-site
建议总结:
- 开发/测试:使用
python3 -m http.server或 Flask - 生产环境:使用 Nginx(性能好、资源占用低)
- 简单部署:使用 systemd 管理Python服务
- 现代化部署:使用Docker容器化
Nginx的优势:
- 高性能,专为静态文件优化
- 低内存占用
- 支持HTTPS、缓存、压缩等高级功能
- 易于配置和维护
对于纯静态HTML文件,Nginx是最佳选择,除非你需要Python的动态功能。
CLOUD技术笔记