Skip to main content
 首页 » 编程设计

python之mitmproxy 将请求重定向到本地主机并设置主机 header

2025年04月02日13del

我在本地端口 8181 上运行一个 http 服务器。我在我的设备上配置了 mitmproxy,现在我需要将来自特定域的请求转发到我的本地服务器实例。所以我正在使用描述的请求重定向示例脚本 here :

def request(flow): 
    # pretty_host takes the "Host" header of the request into account, 
    # which is useful in transparent mode where we usually only have the IP 
    # otherwise. 
 
    # Method 2: Redirect the request to a different server 
    if flow.request.pretty_host.endswith("mydomain.com"): 
        flow.request.headers["Host"] = flow.request.headers 
        flow.request.host = "localhost" 
        flow.request.port = 8181 
        flow.request.scheme = 'http' 

这可行,但我需要将 Host header 设置为原始请求主机,因此我遵循了描述的添加 header 示例 here做这样的

flow.request.headers["Host"] = flow.request.headers 

但是当在 mitmproxy 中时,我无法在请求中看到这个 header 集,而且我也没有在 localhost 服务器日志中得到它。

所以我想做的和 cURL

一样
curl -b c -c c "http://localhost:8181/something" -H "Host: mydomain.com" 

为了至少拥有所需的请求 header ,例如

*   Trying ::1... 
* Connected to localhost (::1) port 8181 (#0) 
> GET /something HTTP/1.1 
> Host:mydomain.com 
> User-Agent: curl/7.43.0 
> Accept: */* 

请您参考如下方法:

尝试:flow.request.headers["Host"] = ["mydomain.com"] 引用:https://github.com/mitmproxy/mitmproxy/blob/v0.9.2/examples/redirect_requests.py