Laravel 如何从子域名 URL 中删除“api”前缀

问题描述 投票:0回答:4

我创建了一个 Laravel 应用程序,它既是 Web 应用程序,又为 android 和 iOS 平台提供 REST API。

我有两个路由文件,一个是 api.php,另一个是 web.php,路由 pi.php 路由如下:

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

配置的 nginx 服务块可以在这里看到

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;
}

}

我能够使用

http://example.com
(对于 Web 应用程序)和
http://api.example.com/api/cities
(对于 REST API)来访问我的应用程序。但子域 URL 包含 api 作为前缀,如下所示。

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

但是我想要我的子域像这样

http://api.example.com/cities
(我想要子域URL中的
remove
api前缀)。

在 api 路由的 RouteServiceProvide.php 中删除前缀

api
是正确的方法吗?

或者他们有什么正确的方法来实现这个吗?

环境详情 Laravel 5.5(LTS) PHP 7.0

laravel laravel-5.5 laravel-routing
4个回答
57
投票

它只是一个前缀,用于区分你的 api 路由和其他路由。您可以在此处添加与

api
不同的内容。

app\Providers\RouteServiceProvider
中更改此功能:

   /**
     * 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'));
    }

删除前缀行:

   /**
     * 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'));
    }

8
投票

实际上在 Laravel 8 中,我只是从 App/Providers/RouteServiceProvider.php 中的前缀中删除 api

Route::prefix('api')
            ->middleware('api')
            ->namespace($this->namespace)
            ->group(base_path('routes/api.php'));

Route::prefix('/')
            ->middleware('api')
            ->namespace($this->namespace)
            ->group(base_path('routes/api.php'));

4
投票

如果您希望整个应用程序成为删除“/api”前缀的 api,还请记住将整个应用程序列入白名单,以便在 config/cors.php 文件中进行 CORS 检查

在config/cors.php中

 'paths' => ['*'],

0
投票

对于那些在 Laravel 11 中开发仅 API 应用程序的人,在 bootstrap/app.php 文件中,您可以替换以下内容:

->withRouting(
    web: __DIR__.'/../routes/web.php',
    api: __DIR__.'/../routes/api.php',
    commands: __DIR__.'/../routes/console.php',
    health: '/up',
)

对此:

->withRouting(
    api: __DIR__.'/../routes/api.php',
    apiPrefix: '',
    commands: __DIR__.'/../routes/console.php',
    health: '/up',
)
© www.soinside.com 2019 - 2024. All rights reserved.