redirects in wsgi config files


I have two custom domains that pointing at the same flask based application. I have two different web apps in PA and this is working fine.

I'd like one of the custom domain to point to a different endpoint in my app:

domain_1 -> /domain_1/home

For a number of reasons, I'd like to avoid handling this in flask, and I've written some simple redirect code that sits in the wsgi file for domain_1 and it's causing redirect loops when I try to access it:

# Middleware for redirecting from root to /home
class RootRedirectMiddleware(object):
    def __init__(self, app, target_url): = app
        self.target_url = target_url

    def __call__(self, environ, start_response):
        path = environ.get('PATH_INFO', '')
        # print(f'Received request for {path}')  # Debugging output

        if path == '/':
            # print(f'Redirecting to {self.target_url}')  # Debugging output
            response = Response('Redirecting...', 302, {'Location': self.target_url})
            return response(environ, start_response)

        return, start_response)

# Applying the middleware
application = RootRedirectMiddleware(flask_app, 'https://domain_1/home')

I don't think the two domains have anything to do with this but just want to be clear about the configuration.

Any advice on if this is possible? Thanks!

If I'm understanding you right you want

https://domain_1/home to map to /home in your urls


https://domain_2/home to map to /domain_2/home in your urls?

Is that right?

Have you thought about loading a different set of urls in your app based on some environment variable?

Not quite -- I want https://domain_2/ to map to https://domain_2/home because domain2 has a different entry point into the app.

How would the environment variable idea work?

@sboyd -- any thoughts? Thanks!

Sorry for having dropped this! You mentioned domain_2 in your last post, but the WSGI code in your first is for domain_1 -- is that a typo in one of those cases?

Assuming it is, what do you see if you enable those debug prints? It might help to add the flush=True kwarg to the end to avoid buffering on the output stream to the log -- they'll go to the website's server log.

no worries -- some more info:

let's just use domain_1 as the example -- it doesn't really matter but I wanted to be clear that there were two domains pointing at the same web app and we want the forwarding behavior for just one of them.

the debug messages seem to indicate the redirect is happening:

2024-03-28 19:26:40 Received request for /                            
2024-03-28 19:26:40 Redirecting.../home

But browsers get stuck in redirect loops.

What do you see in browser dev tools? What requests and responses?

I think we're going to solve this a different way. thanks for the help!

Cool, thanks for letting us know!