URL重写:拆分路径作为子域名实现请求代理的最简方法是什么?
请求代理转发最简实现方案
核心逻辑:从原始请求路径中提取第二级路径段作为目标域名前缀,剥离原始路径的前两级路径段后,将剩余路径和请求参数拼接到目标域名后完成转发。
方案1:Nginx 配置(生产环境首选)
仅需在对应站点配置块中添加如下规则即可:
server { listen 443 ssl; server_name example.com; # 此处可补充你的SSL证书、日志等基础配置 location ~ ^/path/([^/]+)/(.*)$ { # 第一个捕获组匹配path2,第二个捕获组匹配后续路径 proxy_pass https://$1.different.com/$2$is_args$args; proxy_set_header Host $1.different.com; proxy_ssl_server_name on; # 适配目标域名的SNI校验 } }
修改后重载Nginx配置即可生效。
方案2:Caddy 配置(最简部署,无需手动处理SSL)
Caddy会自动处理证书申请续期,配置更精简:
example.com { # 正则匹配路径,捕获对应参数 @proxyRule path_regexp proxy ^/path/([^/]+)/(.*)$ reverse_proxy @proxyRule https://{re.proxy.1}.different.com { rewrite * /{re.proxy.2}{query} header_up Host {re.proxy.1}.different.com } }
直接启动Caddy加载配置即可使用。
方案3:临时测试方案(Python 单文件)
适合本地临时验证场景,安装flask、requests依赖后即可运行:
from flask import Flask, request import requests app = Flask(__name__) @app.route('/path/<path2>/<path:filepath>') def proxy(path2, filepath): target_url = f"https://{path2}.different.com/{filepath}" resp = requests.request( method=request.method, url=target_url, params=request.args, headers={k:v for k,v in request.headers if k.lower() != 'host'}, data=request.get_data(), cookies=request.cookies, allow_redirects=False ) return resp.content, resp.status_code, resp.headers.items() if __name__ == '__main__': app.run(port=443, ssl_context='adhoc')
内容的提问来源于stack exchange,提问作者Balázs Németh
相关产品推荐
相关产品推荐

