Sub-Domain Routing Laravel 5

3.5k views Asked by At

I have been testing sub-domain routing functionality in Laravel 5 and have had success with the following code as described in the docs. When the user visits {username}.mysite.com, the user profile view is shown as expected.

Route::group(['domain' => '{username}.{tld}'], function () {
    Route::get('user/{id}', function ($username, $id) {
        //
    });
});

But, I was expecting a bit of different behavior from what I am experiencing. When the user visits the site through the sub-domain, all of the links in my views now retain the sub-domain within them. All of the other links like {username}.mysite.com/home and {username}.mysite.com/login etc... are fully functional, but I don't understand why Laravel is populating all of my links with the sub-domain and/or how I can get rid of this and only retain the sub-domain for just the single route. I want all of the other links in my views to be like mysite.com/home and mysite.com/login. I was hoping to just use {username}.mysite.com as a quick access point for site visitors, not to retain it in all views.

What can I do to change this behavior?

3

There are 3 answers

7
Martin Bean On

Move routes you don’t want prefixing with the subdomain outside of the route group:

// These routes won’t have the subdomain
$router->controllers([
    'auth' => 'Auth\AuthController',
    'password' => 'Auth\PasswordController',
]);

// These routes WILL have the subdomain
$router->group(['domain' => '{username}.{tld}'], function ($router) {
    $router->get('/', 'UserDashboard@index');

    $router->controller('account', 'AccountController');

    $router->resource('users', 'UserController');
});
0
ankhzet On

You forgot to redirect user... So:

First, as Martin Bean suggested, exclude undesired controllers from sub-domained group.

Second, after user's successful login - redirect him to address without subdomain. You can do that by overriding auth middleware with yours implementation (which must implement TerminableMiddleware interface).

I. e.:

  1. User was on page https://auth.example.com and logined.
  2. Your's override of auth middleware checks for succesful login.
  3. ... and redirects user to https://example.com/home or whatever...

That should be enough.

0
user3691644 On

I found the problem where all of my links/routes were being prefixed with the subdomain, even when they were outside of the route group. The issue is with the Illuminate HTML link builder. It renders relative links rather than full absolute links.

So instead of using: {!! HTML::link('contact', 'Contact Us') !!}

I should have used: {!! HTML::linkRoute('contact_route_name', 'Contact Us') !!}

The linkRoute() function takes into consideration the route group and applies the subdomain as required.