初始的www域名详见:thinkphp6从git到搭建成功,保姆级教程
一、新增二级域名配置
1、到nginx配置的目录 cd /usr/local/etc/nginx/servers 新增一个api.tp6test.com的域名
# 新增 API 子域名配置
server {
listen 80;
server_name api.tp6test.com; # 子域名
root /Users/boolean/myphp/online/tp6test.com/public;
index index.php index.html;
location / {
if (!-e $request_filename) {
rewrite ^(.*)$ /index.php?s=$1 last;
break;
}
}
# 安全禁止访问敏感目录
location ~ ^/(app|application|config|runtime|extend|vendor)/ {
deny all;
return 403;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
# PHP 解析
location ~ \.php$ {
root /Users/boolean/myphp/online/tp6test.com/public;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include fastcgi_params;
}
}
2、重启nginx
nginx -s reload
3、编辑hosts解析域名
vim /etc/hosts
加入配置: 127.0.0.1 api.tp6test.com
二、 thinkphp6框架代码改动
1、安装多应用模式扩展
#安装多应用模式扩展think-multi-app。
composer require topthink/think-multi-app
2、打开文件config/app.php配置domain_bind改掉
'domain_bind' => [
'www.tp6test.com' => 'index', // www主站 index 应用
'api.tp6test.com' => 'api', // api子域名 api 应用
],
3、创建api目录文件
api:app/api/controller/Index.php
<?php
namespace app\api\controller;
class Index
{
public function index()
{
return json([
'msg' => 'API 子域名访问成功',
'domain' => request()->host()
]);
}
}
访问api.tp6test.com结果
4、创建www主站index目录文件:app/index/controller/Index.php
<?php
namespace app\controller;
namespace app\index\controller;
use app\BaseController;
class Index extends BaseController
{
public function index()
{
// echo phpinfo();
return '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:) </h1><p> ThinkPHP V' . \think\facade\App::version() . '<br/><span style="font-size:30px;">16载初心不改 - 你值得信赖的PHP框架</span></p><span style="font-size:25px;">[ V6.0 版本由 <a href="https://www.yisu.com/" target="yisu">亿速云</a> 独家赞助发布 ]</span></div><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="ee9b1aa918103c4fc"></think>';
}
public function hello($name = 'ThinkPHP6')
{
return 'hello,' . $name;
}
}
访问www.tp6test.com结果