2

I already have the answer, I would like to share the solution with those who need it.

How to use multiple domains with different pages and routes in Laravel?

1
  • 2
    It is reasonable that those who vote against say why, I am still contributing to this site, and I have no obligation, do a brief survey and you will see that questions with this objective have not been answered or have been poorly answered. Aug 16, 2020 at 21:51

1 Answer 1

8

I spent many hours looking for solutions, but nothing concrete, always with complex and messy codes, in the end I developed a practical solution with clean code.

1 - Firstly, it is necessary to centralize the laravel in a single domain, then you must point the other domains to the main domain, you can access your dns manager and use the CNAME record for this.

2 - In your Laravel you must create a Controller the home page with the following content, replacing what is necessary:

/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index(Request $request)
{
    $origin = array("mydomain.com", "mydomain2.com");
    $domain = parse_url(request()->root())['host'];

    if (in_array($domain, $origin)) {
        if ($domain === 'mydomain.com') {
            return view('myview'));
        } 
        if ($domain === 'mydomain2.com') {
            return view('myview2'));
        } 
    } else{ 
        return view('unauthorized');
    } 
}

3 - Finally (optional), create a route with the urls that will be accessible only by that domain, do so:

Route::group(array('domain' => 'mydomain.com'), function () {
    /* routes here */
    Route::get('/', 'YouController@index');
});

Route::group(array('domain' => 'mydomain2.com'), function () {
    /* routes here */
    Route::get('/', 'YouController@index');
});

You must change mydomain.com and mydomain2.com to the domain you want, else{} you must replace unauthorized with a valid view, this is what will appear when the domain is not listed, if you want you can do the o server also shows nothing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.