Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

acupofcode's avatar

Send all requests to another server

Hey guys, I need to redirect all requests on production to another server for authentification reasons.. For now I'm using a middleware that does the redirection. Is there any other way that might be better?

Let's say I have a menu item that links to http://localhost:8080/page2 that request actually should go to http://localhost:1234/page2. This server checks if the user is logged in and redirects the request back to http://localhost:8080/page2. I need to make sure that EVERY request goes to http://localhost:1234 on production, but only if env('APP_ENV') is prod.

So I wrote the following middleware and added it to my route's middleware which works fine.

<?php

namespace App\Http\Middleware;

use Closure;

class RequestRedirect
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(env('APP_ENV') == 'prod' && !str_contains($request->url(), env('REQUEST_URL'))) {
            return redirect(env('REQUEST_URL', '') . $request->path());
        }
        
        return $next($request);
    }
}

Is there another, maybe better, way to handle it? I was thinking about generating the links on e.g. menu items to be http://localhost:1234/page2 so the request actually goes directly to the other server instead of being redirected from my application?

Any solutions, hints, tips, ideas are welcome! =)

0 likes
4 replies
bobbybouwmann's avatar

Well this should actually happen on server level instead of application level. You probably know which server is running the production environment so you can configure it in either your nginx or your apache.

However I see one problem here. Wouldn't you create a redirect loop here? How does your production server know that the user is authenticated after the redirect? It will be send back to the same url right?

1 like
acupofcode's avatar

There is some weird database stuff going on at this client when it comes to authentification.. It's a self-developed 20years old single sign on authentification "framework".. That's why I need to redirect all requests to the other server.

If I do the redirection on the server, how to use routing in my application? With a middleware which redirects to my application if the request comes from the other host?

acupofcode's avatar

Dang, I didn't think of using a reverse proxy.. Thanks!

Please or to participate in this conversation.