I am trying to redirect one page to another by using mitmproxy and Python. I can run my inline script together with mitmproxy without issues, but I am stuck when it comes to changing the URL to another URL. Like if I went to google.com it would redirect to stackoverflow.com
def response(context, flow):
print("DEBUG")
if flow.request.url.startswith("http://google.com/"):
print("It does contain it")
flow.request.url = "http://stackoverflow/"
This should in theory work. I see http://google.com/
in the GUI of mitmproxy (as GET) but the print("It does contain it")
never gets fired.
When I try to just put flow.request.url = "http://stackoverflow.com"
right under the print("DEBUG")
it won't work neither.
What am I doing wrong? I have also tried if "google.com" in flow.request.url
to check if the URL contains google.com
but that won't work either.
Thanks
Setting the
url
attribute will not help you, as it is merely constructed from underlying data. [EDIT: I was wrong, see Maximilian’s answer. The rest of my answer should still work, though.]Depending on what exactly you want to accomplish, there are two options.
(1) You can send an actual HTTP redirection response to the client. Assuming that the client understands HTTP redirections, it will submit a new request to the URL you give it.
(2) You can silently route the same request to a different host. The client will not see this, it will assume that it’s still talking to
google.com
.These snippets were adapted from an example found in mitmproxy’s own GitHub repo. There are many more examples there.
For some reason, I can’t seem to make these snippets work for Firefox when used with TLS (
https://
), but maybe you don’t need that.You can set
.url
attribute, which will update the underlying attributes. Looking at your code, your problem is that you change the URL in theresponse
hook, after the request has been done. You need to change the URL in therequest
hook, so that the change is applied before requesting resources from the upstream server.The following
mitmproxy
script willmydomain.com
tonewsite.mydomain.com
/getjson?
to a new one `/getxmlOverwrite the request header
Host
to pretend to be the origi