Search code examples
laravelroutessubdomain

Laravel subdomain endpoint keeps redirecting with 301 error


I have a working Laravel app and have introduced a subdomain (api.mysite.com) to handle programmatic access by my users. I've set up a route group at the top of my routes file:

Route::group(['domain' => 'api.' . config('app.domain'), 'middleware' => 'api'], function () {
    Route::get('/some-endpoint','APIController@someHandler');
});

This arrangement works locally.

I added an A record to my DNS records pointing the api subdomain at my site's IP:

A Record    api    XX.XXX.XXX.XXX    Automatic

The problem is that when I try to access api.mysite.com/some-endpoint when deployed to production the site responds with a 301 and tries to redirect me to mysite.com/some-endpoint which doesn't have a route in my routes file and thus replies with a 404.


Solution

  • The problem existed in my nginx config file. In the server section I needed to change the line

    server_name mysite.com;
    

    to

    server_name .mysite.com;
    

    See this related question. Be aware, however, that the wildcard server name lookups resulting from names like .mysite.com are slower than those resulting from explicitly defined names like mysite.com www.mysite.com api.mysite.com.

    See also the nginx documentation:

    A special wildcard name in the form “.example.org” can be used to match both the exact name “example.org” and the wildcard name “*.example.org”.