Laravel subdomain routing redirect to 404 if route not in subdomain

I am using subdomain routing in my app and will like for requests to subdomain routes to be redirected to a 404 page if the requested route does not exists in the subdomain. Here is the scenario:

// Subdomain routes
Route::domain('app.mysite.test')->group(function(){
    Route::get('/', function(){
        dd("Home page for subdomain");
    });

    Route::get('/404', function(){
        dd("Subdomain 404");
    });
    //... other subdomain routes here
});

// Top domain routes
Route::group(['namespace' => 'Site'], function(){
    Route::get('/', function(){
        dd("Main site home page");
    });

    Route::get('/login', function(){
        dd("Main site LOGIN page");
    });
});

In the above scenario, if someone tries to access a route that does not exist in the subdomain (eg http://app.mysite.test/login), they will be automatically redirected to the login page of the main site (ie: http://mysite.test/login).

My question is: How to I redirect users to http://app.mysite.test/404 if they try to access http://app.mysite.test/login?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I think I found a solution: At the end of the Subddomain route group, add a catchall expression that basically catches everything that’s not in the subdomain routes and renders the 404 page. Make sure this catchall route is at the end of your subdomain routes:

// Subdomain routes
Route::domain('app.mysite.test')->group(function(){
    Route::get('/', function(){
        dd("Home page for subdomain");
    });

    //Route::get('/404', function(){
    //    dd("Subdomain 404");
    //});
    //... other subdomain routes here

    // ADD THE CATCHALL REGEX HERE
    Route::get("{catchall}", function(){
        dd("404 page from subdomain");
    })->where('catchall', '(.*)');
});

// Top domain routes
Route::group(['namespace' => 'Site'], function(){
    Route::get('/', function(){
        dd("Main site home page");
    });

    Route::get('/login', function(){
        dd("Main site LOGIN page");
    });
});


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x