How to redirect all Laravel routes to a new subdomain using Laravel routing system?
P粉310931198
P粉310931198 2023-09-02 11:45:56
0
1
505
<p>Redirect all Laravel routes to the same route, but change the base URL. </p> <p>I want to move my Laravel project from domain to subdomain What is the best way to redirect all requests on the last domain to the same new subdomain. </p> <p>For example, if a user sends a request to this URL</p> <pre class="brush:php;toolbar:false;">mydomain.com/page/1</pre> <p>Redirect to this URL</p> <pre class="brush:php;toolbar:false;">subdomain.mydomain.com/page/1</pre> <p>I prefer to handle it inside the Laravel project. Not an NGINX configuration. </p>
P粉310931198
P粉310931198

reply all(1)
P粉052686710

To handle this at the Laravel level you can use middleware. Middleware provides a convenient mechanism to inspect and filter HTTP requests entering your application.

Here are examples of how you can do this.

First, create a new middleware by running the following command:

php artisan make:middleware SubdomainRedirectMiddleware

Next, open the newly created file app/Http/Middleware/SubdomainRedirectMiddleware.php and add the redirection logic to the handle method:

public function handle(Request $request, Closure $next)
{
    // Replace 'mydomain' with your actual domain
    if ($request->getHost() === 'mydomain.com') {

        // Replace 'subdomain' with your actual subdomain
        return redirect()->to(str_replace('mydomain.com', 'subdomain.mydomain.com', $request->fullUrl()));
    }

    return $next($request);
}

Then, you need to register this middleware. Open app/Http/Kernel.php and add the following lines to the routeMiddleware array:

protected $routeMiddleware = [
    'subdomain.redirect' => \App\Http\Middleware\SubdomainRedirectMiddleware::class,
];

Route::group(['middleware' => 'subdomain.redirect'], function () {
    // All your routes go here
});

Please replace 'mydomain' and 'subdomain' with your actual domain and subdomain in SubdomainRedirectMiddleware.php.

▽This is a reference https://www.w3schools.in/laravel/middleware

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template