Laravel How to remove "api" Prefix from subdomain URL

Minion picture Minion · Apr 1, 2018 · Viewed 10.6k times · Source

I have created a Laravel application which is both Web application and provides REST APIs to android and iOS platforms.

I have two route files one is api.php and other is web.php and routes\api.php routing as follows:

routes/api.php
    Route::group([
    'domain'=>'api.example.com',
    function(){
        // Some routes ....
    }
);

and nginx serve blocks configured can be seen here

server {
listen 80;
listen [::]:80;

root /var/www/laravel/public;
index index.php;
server_name api.example.com;

location / {
    try_files $uri $uri/ /index.php$is_args$args;
}

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
}

}

I was be able to access my application using http://example.com for web application and http://api.example.com/api/cities for REST API's. But the subdomain URL contains api as prefix as given below.

http://api.example.com/api/cities

But i want to my subdomain like this http://api.example.com/cities (I wanted to remove api prefix from the sub domain URL).

Is it right way to remove prefix api in RouteServiceProvide.php for api routes?

Or is they any right way to implement this?

Environment Details Laravel 5.5 (LTS) PHP 7.0

Answer

Samir Mammadhasanov picture Samir Mammadhasanov · Apr 1, 2018

It's just prefix to differ your api routes from other routes. You can add something different from api to here.

In app\Providers\RouteServiceProvider change this function:

   /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::prefix('api')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }

Remove prefixe line:

   /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }