简体   繁体   中英

How can one intercept an HTTP request, stop the request, and redirect the user to another site?

I am working on a url redirector application, in Python. The idea of this application is simple: when a user performs an http request to a certain domain (eg to https://google.com ), the app stops the request and performs another http request (eg to https://github.com ), thereby redirecting the user to the second page.

Unfortunately, I have looked through SO and I haven't found any question that addresses this issue directly:

Admittedly, I only have some fabricated pseudocode to demonstrate what I wish to do, but it may prove useful:

import requests

original_site = "https://google.com"
redirect_site = "https://github.com"

def redirect_request():
    if requests.get(original_site) == True:
        requests.kill(request.original_site.id)
        requests.get(redirect_site)

I greatly appreciate any suggestions.

EDIT - Here is a clarification of what I mean:

The user runs my python script, which I will call foobar.py , as follows:

python foobar.py

Then the user opens their web browser, and enters the url https://google.com , and as the script is running, the user will not actually visit https://google.com , but be redirected to https://github.com

One option is if you are trying to build a lightweight web app using python where you can mess with HTTP redirects, you can use Flask to accept a GET on a route and then simply do a redirect.

from flask import Flask, redirect
app = Flask(__name__)

@app.route('/')
def index():
    return redirect("https://www.google.com")

But to answer your question more directly, you don't "stop" the initial request. You simply find a way to handle it and serve back a response that you specify.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM