时间:2024-10-22 来源:风信官网 点击: 428次
在laravel项目开发的过程中,为了能更好的展现PC端和移动端不同内容之间的差异,我们通常会使用www.test.com访问PC端的内容,而m.test.com去访问移动端的内容,这种架构的设计方式,能更好的符合搜索引擎的规则,特别是针对百度移动适配规则能有更好的表现。
百度移动适配规则如下:
1. 为提升搜索用户在百度移动搜索的检索体验,会给对应PC页面的手机页面在搜索结果处有更多的展现机会,需要站点向百度提交主体内容相同的PC页面与移动页面的对应关系,即为移动适配。为此,百度移动搜索提供“移动适配”服务,如果您同时拥有PC站和手机站,且二者能够在内容上对应,即主体内容完全相同,您可以通过移动适配工具进行对应关系提交。
2. 自适应站点不需要使用移动适配工具。
通过规则适配,使用正则表达式描述PC-移动URL关系,适用于网站大多数目录页
那么在Laravel中如何去实现,详情如下:
1、在app\http\Controllers文件夹里面创建PC端和移动端不同的控制器文件夹,分别对应PC端的路由文件及移动端路由文件
2、修改app\http\providers\RouteServiceProvider.php文件
<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to your controller routes.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
protected $homeNamespace = 'App\Http\Controllers\Web';//PC端
protected $mNamespace = 'App\Http\Controllers\M';//移动端
/**
* The path to the "home" route for your application.
*
* @var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, etc.
*
* @return void
*/
public function boot()
{
//
parent::boot();
}
/**
* Define the routes for the application.
*
* @return void
*/
public function map()
{
// $this->mapApiRoutes();
// $this->mapWebRoutes();
// 通过判断$_SERVER['HTTP_HOST']的入口来区分www和m
$sld_prefix = explode('.',$_SERVER['HTTP_HOST'])[0];
if('www' == $sld_prefix){
$this->mapHomeRoutes();
}elseif('m' == $sld_prefix){
$this->mapMRoutes();
}
}
/**
* PC端指定路由文件
*/
protected function mapHomeRoutes()
{
Route::middleware('web')
->namespace($this->homeNamespace)
->group(base_path('routes/www.php'));
}
/**
* 移动端指定路由文件
*/
protected function mapMRoutes()
{
Route::middleware('web')
->namespace($this->mNamespace)
->group(base_path('routes/m.php'));
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
/**
* 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'));
}
}
3、在routes目录下创建www.php路由
Route::get('/', 'IndexController@index'); //PC端网站首页
4、在routes目录下创建m.php路由
Route::get('/', 'IndexController@index'); //移动首页
5、测试效果
现在我们已经实现不同域名之间的访问效果。