P粉0526867102023-09-03 00:47:56
To handle this at the Laravel level you can use middleware. Middleware provides a convenient mechanism to inspect and filter HTTP requests entering your application.
Here are examples of how you can do this.
First, create a new middleware by running the following command:
php artisan make:middleware SubdomainRedirectMiddleware
Next, open the newly created file app/Http/Middleware/SubdomainRedirectMiddleware.php and add the redirection logic to the handle method:
public function handle(Request $request, Closure $next) { // Replace 'mydomain' with your actual domain if ($request->getHost() === 'mydomain.com') { // Replace 'subdomain' with your actual subdomain return redirect()->to(str_replace('mydomain.com', 'subdomain.mydomain.com', $request->fullUrl())); } return $next($request); }
Then, you need to register this middleware. Open app/Http/Kernel.php and add the following lines to the routeMiddleware array:
protected $routeMiddleware = [ 'subdomain.redirect' => \App\Http\Middleware\SubdomainRedirectMiddleware::class, ]; Route::group(['middleware' => 'subdomain.redirect'], function () { // All your routes go here }); Please replace 'mydomain' and 'subdomain' with your actual domain and subdomain in SubdomainRedirectMiddleware.php.
▽This is a reference https://www.w3schools.in/laravel/middleware