经过网上查资料及自己摸索,终于实现了自己所想要实现的前后台分离
PS:在模板这一块感觉还不够完美,如果后边找到更好的方法,到时会到这里更新。
前台域名:www.test6.local
后台域名:admin.test6.local
环境为:Win7x64+PHPStudy2018 nginx+PHP7.0
nginx.conf增加域名解析
#test6 www
server {
listen 80;
server_name www.test6.local;
root "d:/data/www/test6/public/www";
index index.html index.htm index.php;
error_page 404 /404.html;
location = /404.html {
return 404 'Sorry, File not Found!';
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html; # windows dir
}
location / {
try_files $uri $uri/ /index.php?$query_string;
}
#location / {
# try_files $uri @rewrite;
#}
#location @rewrite {
# set $static 0;
# if ($uri ~ \.(css|js|jpg|jpeg|png|gif|ico|woff|eot|svg|css\.map|min\.map)$) {
# set $static 1;
# }
# if ($static = 0) {
# rewrite ^/(.*)$ /index.php?s=/$1;
# }
#}
location ~ /Uploads/.*\.php$ {
deny all;
}
location ~ \.php/ {
if ($request_uri ~ ^(.+\.php)(/.+?)($|\?)) { }
fastcgi_pass 127.0.0.1:9000;
include fastcgi_params;
fastcgi_param SCRIPT_NAME $1;
fastcgi_param PATH_INFO $2;
fastcgi_param SCRIPT_FILENAME $document_root$1;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.ht {
deny all;
}
}
创建两个文件夹
/public/www
/public/admin
将index.php拷到上述文件夹中,注意修改require路径加../
前后分离的关键点在
/app/Providers/RouteServiceProvider.php
增加或修改如下代码:
//前台命名空间
protected $www_namespace = 'App\Http\Controllers\Www';
//后台命名空间
protected $admin_namespace = 'App\Http\Controllers\Admin';
//$this->mapApiRoutes();
//$this->mapWebRoutes();
//判断域名前缀 如admin,www
$url_prefix = explode('.',$_SERVER['HTTP_HOST'])[0];
if($url_prefix=='www'){
$this->mapWwwRoutes();
}else if($url_prefix=='admin'){
$this->mapAdminRoutes();
}
//前台路由
protected function mapWwwRoutes(){
//echo 2333;exit;
Route::middleware('web')
->namespace($this->www_namespace)
->group(base_path('routes/www.php'));
}
//后台路由
protected function mapAdminRoutes(){
//echo 2333;exit;
Route::middleware('web')
->namespace($this->admin_namespace)
->group(base_path('routes/admin.php'));
}
/routes下新增两个文件www.php admin.php
路由自己发挥,如:
Route::get('/', 'IndexController@index');
/app/Htpp/Controllers下新增两个文件夹,为Www和Admin
文件如:
【Admin下Controller.php修改】
namespace App\Http\Controllers\Admin;
【Admin下IndexController.php修改】
namespace App\Http\Controllers\Admin;
前后台模板页分离测试
在resources/views下新建Www和Admin文件夹,将模板文件放入
在前述控制器中这样写:
return view('Www/index',compact('title','list','info','email'));
这样就达到了前后台分离的目的。