Python Flask:如何批量实现多URL重定向?
Flask批量实现URL重定向方案
如果需要批量处理大量URL重定向,完全不用一个个写redirect路由,下面给你几种实用方案:
1. 映射字典+通用路由
先把所有重定向规则整理成字典,再通过一个通用路由统一处理:
from flask import Flask, redirect, request app = Flask(__name__) # 存放所有重定向规则的字典 REDIRECT_RULES = { "/example-1": "https://subdomain.example.com/example-1", "/example-2": "https://subdomain.example.com/example-2", "/example-3": "https://subdomain.example.com/example-3", # 后续直接添加新规则即可 } @app.route("/<path:req_path>") def batch_redirect(req_path): full_path = f"/{req_path}" if full_path in REDIRECT_RULES: # 301为永久重定向(对SEO友好),临时重定向可改用302 return redirect(REDIRECT_RULES[full_path], code=301) # 未匹配到的路径返回404,或留空让其他路由处理 return "页面不存在", 404
2. 全局钩子拦截请求
如果不想占用通用路由,用before_request钩子在请求处理前检查,更灵活:
from flask import Flask, redirect, request app = Flask(__name__) REDIRECT_RULES = { "/example-1": "https://subdomain.example.com/example-1", "/example-2": "https://subdomain.example.com/example-2", "/example-3": "https://subdomain.example.com/example-3", } @app.before_request def handle_redirects(): current_path = request.path if current_path in REDIRECT_RULES: return redirect(REDIRECT_RULES[current_path], code=301) # 未匹配到则正常走后续路由逻辑
3. 路径规则统一时的极简方案
像你例子里的情况,旧URL和新URL仅域名不同、路径完全一致,不用维护字典,直接动态替换即可:
from flask import Flask, redirect, request app = Flask(__name__) @app.before_request def domain_redirect(): # 检查当前请求域名是否为旧域名 if request.host == "www.example.com": # 直接替换域名生成新URL new_url = request.url.replace("www.example.com", "subdomain.example.com") return redirect(new_url, code=301)
内容的提问来源于stack exchange,提问作者Howard S
相关产品推荐
相关产品推荐

