在 Ubuntu 上开启本地 HTTP 服务器有多种简单方法,如下:
一、开启方法
方法 1:使用 Python 内置模块(推荐)
Python 3(Ubuntu 默认自带:
# 进入目标目录(例如 ~/mysite)
cd ~/mysite
# 启动服务器(默认端口 8000)
python3 -m http.server
# 指定端口(如 9000)
python3 -m http.server 9000
# 允许局域网访问(监听所有接口)
python3 -m http.server 8000 --bind 0.0.0.0
Python 2(旧版兼容):
python -m SimpleHTTPServer 8000
方法 2:使用 PHP 内置服务器
# 进入目标目录
cd ~/mysite
# 启动服务器(默认端口 8000)
php -S localhost:8000
# 允许局域网访问
php -S 0.0.0.0:8000
方法 3:使用 Node.js http-server
(需安装 Node.js)
# 安装 http-server
sudo npm install -g http-server
# 启动服务(进入目标目录后)
http-server -p 8000
方法 4:使用 Ruby 内置服务器
ruby -run -e httpd . -p 8000
访问服务器:
- 本机访问:浏览器打开
http://localhost:8000
- 局域网访问:
http://<你的IP>:8000
(通过ip a
查看本机 IP)
防火墙设置(如需允许外部访问):
# 允许端口 8000
sudo ufw allow 8000
终止服务器:
在终端按 Ctrl + C
即可停止服务。
适用场景对比:
方法 | 优点 | 缺点 |
---|---|---|
Python | 无需安装,系统自带 | 功能简单(仅静态文件) |
PHP | 支持 PHP 动态页面 | 需安装 PHP |
Node.js | 功能丰富,支持实时刷新 | 需安装 Node.js 和 npm |
Ruby | 简单快捷 | 需安装 Ruby |
二、Python 测试脚本–打印get/post 信息
创建脚本 http_server.py
#!/usr/bin/env python3
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import cgi
class RequestHandler(BaseHTTPRequestHandler):
def _log_request(self):
"""记录并打印所有请求信息"""
print(f"\n{'='*50}\n收到 {self.command} 请求:")
print(f"客户端地址: {self.client_address[0]}:{self.client_address[1]}")
print(f"请求路径: {self.path}")
print("请求头:")
for key, value in self.headers.items():
print(f" {key}: {value}")
def _send_response(self, message):
"""发送响应并记录"""
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
response = json.dumps({"status": "success", "message": message})
self.wfile.write(response.encode('utf-8'))
print(f"响应内容: {response}")
def do_GET(self):
"""处理 GET 请求"""
self._log_request()
self._send_response("GET 请求已处理")
def do_POST(self):
"""处理 POST 请求"""
self._log_request()
# 获取内容类型和长度
content_type = self.headers.get('content-type')
content_length = int(self.headers.get('content-length', 0))
# 读取 POST 数据
post_data = self.rfile.read(content_length)
# 解析不同格式的数据
if content_type == 'application/json':
data = json.loads(post_data.decode('utf-8'))
print("JSON 数据:", json.dumps(data, indent=2))
elif content_type == 'application/x-www-form-urlencoded':
data = dict(cgi.parse_qs(post_data.decode('utf-8')))
print("表单数据:", data)
elif content_type == 'multipart/form-data':
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD': 'POST'}
)
data = {key: form[key].value for key in form}
print("多部分表单数据:", data)
else:
print("原始数据:", post_data.decode('utf-8'))
self._send_response("POST 请求已处理")
def run_server(port=8000):
"""启动服务器"""
server_address = ('', port)
httpd = HTTPServer(server_address, RequestHandler)
print(f"服务器启动,监听端口 {port}...")
print("支持 GET/POST 请求,按 Ctrl+C 停止")
httpd.serve_forever()
if __name__ == '__main__':
run_server(port=8000)
或者
#!/usr/bin/env python3
from http.server import HTTPServer, SimpleHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
import json
import traceback
class CustomHandler(SimpleHTTPRequestHandler):
# 禁用默认日志
def log_message(self, format, *args):
pass
def handle_request(self):
"""处理请求并打印详细信息"""
try:
# 打印请求行
print(f"\n----- {self.requestline} -----")
# 打印请求头
print("Headers:")
for header, value in self.headers.items():
print(f" {header}: {value}")
# 处理请求体
content_length = self.headers.get('Content-Length')
request_body = None
if content_length:
content_length = int(content_length)
if content_length > 0:
request_body = self.rfile.read(content_length)
# 尝试解析不同格式的请求体
content_type = self.headers.get('Content-Type', '').lower()
print(f"Body ({content_type}):")
if 'application/json' in content_type:
try:
body_data = json.loads(request_body.decode('utf-8'))
print(json.dumps(body_data, indent=2, ensure_ascii=False))
except json.JSONDecodeError:
print(f"JSON解析失败: {request_body.decode('utf-8', errors='ignore')[:100]}...")
elif 'application/x-www-form-urlencoded' in content_type:
body_data = parse_qs(request_body.decode('utf-8'))
print(json.dumps(body_data, indent=2, ensure_ascii=False))
elif 'multipart/form-data' in content_type:
boundary = content_type.split('boundary=')[1].encode()
parts = request_body.split(boundary)
for i, part in enumerate(parts):
if part.strip():
print(f" Part {i}: {part.decode('utf-8', errors='ignore')[:100]}...")
else:
try:
print(request_body.decode('utf-8', errors='ignore'))
except UnicodeDecodeError:
print(f"二进制数据 (长度: {content_length} bytes)")
# 根据HTTP方法分发处理
if self.command == 'GET':
self.handle_get()
elif self.command == 'POST':
self.handle_post(request_body)
else:
self.send_error(405, "Method Not Allowed")
except Exception as e:
print(f"处理请求时出错: {str(e)}")
traceback.print_exc()
self.send_error(500, "Internal Server Error")
def handle_get(self):
"""处理GET请求"""
# 解析URL路径和查询参数
parsed_url = urlparse(self.path)
path = parsed_url.path
query_params = parse_qs(parsed_url.query)
# 构建响应数据
response_data = {
"method": "GET",
"path": path,
"query_params": query_params,
"message": "GET请求处理成功"
}
# 返回JSON响应
self.send_json_response(200, response_data)
def handle_post(self, request_body):
"""处理POST请求"""
content_type = self.headers.get('Content-Type', '').lower()
parsed_data = None
# 解析请求体
if 'application/json' in content_type and request_body:
try:
parsed_data = json.loads(request_body.decode('utf-8'))
except json.JSONDecodeError:
self.send_json_response(400, {"error": "无效的JSON格式"})
return
elif 'application/x-www-form-urlencoded' in content_type and request_body:
parsed_data = parse_qs(request_body.decode('utf-8'))
# 构建响应数据
response_data = {
"method": "POST",
"path": self.path,
"content_type": content_type,
"data": parsed_data,
"message": "POST请求处理成功"
}
# 返回JSON响应
self.send_json_response(200, response_data)
def send_json_response(self, status_code, data):
"""发送JSON格式响应"""
try:
json_data = json.dumps(data, ensure_ascii=False, indent=2).encode('utf-8')
self.send_response(status_code)
self.send_header('Content-Type', 'application/json; charset=utf-8')
self.send_header('Content-Length', len(json_data))
self.end_headers()
self.wfile.write(json_data)
except Exception as e:
print(f"发送响应时出错: {str(e)}")
self.send_error(500, "Failed to generate response")
def do_GET(self):
self.handle_request()
def do_POST(self):
self.handle_request()
if __name__ == '__main__':
server_address = ('', 8000)
httpd = HTTPServer(server_address, CustomHandler)
print('服务器运行中,端口: 8000')
print('按 Ctrl+C 停止服务器')
try:
httpd.serve_forever()
except KeyboardInterrupt:
print('\n服务器已停止')
httpd.server_close()
脚本 http_server.py
赋权限。
Ubuntu 下 执行 脚本
./http_server.py
或者
python3 ./http_server.py
Windows10 下 执行 脚本
.\http_server.py
或者
python .\http_server.py
打开 Windows PowerShell
,进入脚本目录下,输入指令即可。