Search code examples
laravelapache.htaccesssubdomain

How to enable the Laravel app working in a subdomain to handle the requests from another subdomain, without changing the URL in the browser?


I have my Laravel app working in the admin subdomain:

admin.mysite.com

I would like to enable my Laravel app to also handle the requests coming from another subdomain; client.mysite.com, for example. I'm trying to utilize the Apache Rewrite feature for this; thus, I've created the following .htaccess file in the main directory of the "client" subdomain:

# file: /client/public/.htaccess
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^/?([a-zA-Z][a-zA-Z0-9]*)/?(.*)$  https://admin.mysite.com/bu/$1/$2 [L,NC]
</IfModule>

That works, but I definitely don't want the URL to be changed in the browser. To that end, I tried the [P] flag to no success. Eventually, I removed the https:// part to avoid redirects*:

RewriteRule ^/?([a-zA-Z][a-zA-Z0-9]*)/?(.*)$  admin.mysite.com/bu/$1/$2 [L,NC]

But then, I get the following error:

Request exceeded the limit of 10 internal redirects due to probable configuration error. Use 'LimitInternalRecursion' to increase the limit if necessary. Use 'LogLevel debug' to get a backtrace.

How to fix the error and make it work? And, is this the right way to accomplish such a task at all? (does it work with POST and all? Is there any better solutions?)


* If you start the substitution argument in the RewriteRule with https:// it will cause a Redirection (it's just like an External Redirect using the [R] flag). This will cause the browser to make a new request, hence changing the URL showed in the address bar.

Also, please consider that my app is on a shared host, thus I might not have access to some low-level features.


Solution

  • Set the DOCUMENT_ROOT of your client.mysite.com to point to the same directory where the main Laravel app resides (in your case, set it to /admin/public). Then utilize the subdomain routing facility in Laravel; the subdomain may be specified by calling the domain() method:

    Route::domain('client.mysite.com')->group(function () {
        Route::get('{username}', function ($username) {
            //
        });
    });