4

How to route api.example.com to example.com/api so i can just

api.example.com/v1/users 

than using

example.com/api/v1/users.

I'm using nginx, thank you.

1
  • Put rewrite ^/api/(.*)$ http://api.example.com/$1 redirect; inside your server block for example.com. Commented Sep 12, 2016 at 5:30

1 Answer 1

4

Ensure these 2 steps are in place.

Check your nginx configuration /etc/nginx/conf.d/example.conf and include the domain in the server_name like so:

server_name example.com api.example.com;

Check that you have a route setup within the routes/api.php file. Using the sub-domain group is optional but be sure that you have the correct routes.

Example of using domain group:

Route::group(['domain' => 'api.example.com'], function () {
    Route::get('/v1/users', ['as' => 'api.users.index', 'uses' => 'UserController@index']);
}

Example without use of domain group and allowing for both URL to point to the same Controller (be sure to define its own route names as per the 'as').

Route::get('/v1/users', ['as' => 'api.users.index', 'uses' => 'UserController@index']);
Route::get('/api/v1/users', ['as' => 'users.index', 'uses' => 'UserController@index']);

Update:

Refer to official Laravel 5.3 documentation regarding the use of sub-domain routes https://laravel.com/docs/5.3/routing#route-group-sub-domain-routing

Sign up to request clarification or add additional context in comments.

3 Comments

thanks for the help, now my nginx has direct the example and api.example to laravel public folder. and for the route, since 5.3 has place the route at routes/web.php and routes/api.php, i must use the web.php to make it works.
Ah.. updated my answer. Didn't realise a change in the routes file structure.
need to use web.php with your solution since api.php can only accessed from example.com/api . you can try it.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.