Search code examples
laravelrest.htaccesshttpweb

How to forward http request from old route to new route retaining http method and queries


I hope i can finally get help over here.

i want to forward all request from old path to new path and retaining the method and queries.

OLD URL PATH:

[POST|GET|PUT|DELETE]: mydomain.com/public/api?key=value

Desired URL PATH:

[POST|GET|PUT|DELETE]: mydomain.com/api?key=value

Please can any one help me with the .htaccess code to achieve above idea.


Solution

  • I finally figured it out from within the app.

    I had to get all request from old url and remove the public path from the url and allow laravel to handle them as a new request such that domain.com/public/api will become domain.com/api.

    Capture requests from old url from RouteServiceProvider.

    ...
    use Illuminate\Support\Facades\Http;
    use Route;
    use Illuminate\Http\Request;
    
    class RouteServiceProvider extends ServiceProvider
    {
         ...
         public function boot()
        {
            $this->configureRateLimiting();
    
            $this->routes(function () {
                Route::middleware('web')
                    ->group(base_path('routes/web.php'));
    
                Route::prefix('api')
                    ->middleware('api')
                    ->group(base_path('routes/api.php'));
    
                // handle apps using old api path
                Route::any('public/api/{any}', function (Request $request) {
                    // remove public from path
                    $paths = explode('/', $request->path());
                    $path = implode('/', array_slice($paths, 1));
                     
                    // update request with new path
                    $request->server->set('REQUEST_URI', $path);
                    $request->server->set('PATH_INFO', $path);
                     
                    // handle as a new request
                    return app()->handle($request);
                  })
                  ->middleware('api')
                  ->where('any', '.*');
            });
        }
      ...
    

    more info from medium post