Search code examples
http-redirectflaskurl-rewritingdnscname

How to permanently redirect all pages of a subdomain to a sub-path of the www domain?


I have this website for instance:

I still host that old site but I moved it here:

I'd like each old page to point to each new page. A permanent redirect like this:

https://www.neuraxle.neuraxio.com/* ==> https://www.neuraxio.com/en/neuraxle/*

Do I need to host a server for this to manually writing a Python Flask app that redirects each URL with a custom rewrite? I'd like to avoid coding this by using DNS. Is there a DNS trick I can use? I use GoDaddy to manage my DNS.

Optional: if there is nothing to be done with DNS, can you provide an example Flask URL handler method? Is there a free hosting service available for me to host this flask app?


Solution

  • This worked, accepted bountied answer is poor:

    @app.before_request
    def redirect_to_new_domain():
        FROM_DOMAINS = ['0.0.0.0:' + str(PORT), 'https://www.neuraxio.com', 'www.neuraxio.com', "neuraxio.com"]
        SUBPATH = "/en/neuraxle"
        TO_DOMAIN = 'www.neuraxle.org'
        urlparts = urlparse(request.url)
        print(urlparts, urlparts.netloc)
        if urlparts.netloc in FROM_DOMAINS and SUBPATH in urlparts.path:
            parsed = urlparts
            parsed = parsed._replace(netloc=TO_DOMAIN)
            parsed = parsed._replace(path=urlparts.path.replace(SUBPATH, ""))
            return redirect(parsed.geturl(), code=301)
    

    Note: my own answer here doesn't completely answer the original question but at least compiles. We also needed this as I answer now, to the exception that we we also have a sub-path to redirect from instead of to.