from fastapi import FastAPI, Request from fastapi.responses import Response, HTMLResponse from fastapi.middleware.cors import CORSMiddleware import requests import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) @app.get("/{full_path:path}") @app.post("/{full_path:path}") async def proxy(request: Request, full_path: str = ""): try: # 构建目标 URL target_url = f"http://beibeioo.top/{full_path}" logger.info(f"Incoming request: {full_path}") logger.info(f"Forwarding to: {target_url}") # 设置请求头 headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Language': 'en-US,en;q=0.5', 'Connection': 'keep-alive', 'Host': 'beibeioo.top' } # 发送请求 response = requests.get(target_url, headers=headers) content_type = response.headers.get('content-type', '') # 如果是静态资源请求 if full_path.endswith(('.js', '.css', '.png', '.jpg', '.jpeg', '.gif', '.ico')): logger.info(f"Serving static file: {full_path}") return Response( content=response.content, media_type=response.headers.get('content-type', 'application/octet-stream'), headers={'Access-Control-Allow-Origin': '*'} ) # 如果是 HTML 内容 elif 'text/html' in content_type: content = response.text # 替换所有资源路径,包括 assets 目录 replacements = [ ('"/assets/', '"assets/'), # 改为相对路径 ('"/static/', '"static/'), # 改为相对路径 ('"/logo.png', '"logo.png'), # 改为相对路径 ('href="/', 'href="'), # 改为相对路径 ('src="/', 'src="'), # 改为相对路径 ] for old, new in replacements: content = content.replace(old, new) # 添加基础路径 base_tag = f'' if '' in content: content = content.replace('', f'{base_tag}') return HTMLResponse( content=content, headers={ 'Access-Control-Allow-Origin': '*', 'Content-Security-Policy': "default-src * 'unsafe-inline' 'unsafe-eval'; img-src * data: blob:;" } ) # 其他类型的内容 else: return Response( content=response.content, media_type=content_type, headers={'Access-Control-Allow-Origin': '*'} ) except Exception as e: logger.error(f"Error occurred: {str(e)}") return Response(content=str(e), status_code=500) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)