且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ServerLess实战:函数计算+NAS搭建无服务器thinkphp5

更新时间:2022-09-18 15:10:02

如果太忙都有可能忘记续费主机或者服务器,而且每次买配置过低或者过高都不合适,所以这次用函数计算+NAS搭建无需续费无存储大小限制无需考虑带宽CPU等性能瓶颈,来搭建常用的tp5

先放懒人包下载,详见附件,上传NAS

1、必备条件
A、开通函数计算与NAS服务
B、绑定函数计算域名
C、挂载NAS到同区域节点的ECS上方便文件的复制粘贴修改操作
D、给账户充钱。函数计算和NAS扣费都是后付费,要保证账户余额
2、函数计算配置详解
A、选择区域创建服务,要和NAS选择同一区域
ServerLess实战:函数计算+NAS搭建无服务器thinkphp5

B、新建服务、绑定NAS
ServerLess实战:函数计算+NAS搭建无服务器thinkphp5
ServerLess实战:函数计算+NAS搭建无服务器thinkphp5
绑定nas的时候写用户不用用他默认的-1,那个读不出来,自己随便定一个ID
C、新建函数、编写函数代码

选择HTTP函数,运行环境选择php7.2,触发器选择任何人,其他随意
以下是函数代码,
<?php
//#自定义的域名,绑定了自定义域名的,可以换成自己自定义的。
$MY_HOST    = "你的地址哈3333.cn-cn-hangzhou.fc.aliyuncs.com";
//#web目录,默认是tp5的public目录,绝对路径,如:/code/public
$WWW_DIR = '/mnt/think5/public';
 
function handler($request, $context){
 
 
$uri  = $request->getAttribute("requestURI");
//return $uri;
$file = explode("?", $uri)[0];
if($file=='/') $uri='/';
$file = $GLOBALS['WWW_DIR'].$file;
 
if(file_exists($file) and $uri!='/'){
    if(strpos($uri,".php")) return php_run(basename($file), $request, $context);#php_run
    return static_run($uri);#static_run
}
 
$request = $request->withAttribute("requestURI", "?s=".$uri);
return php_run('index.php', $request, $context);# php_run
 
}
 
function php_run($name,$request, $context)
{
return $GLOBALS['fcPhpCgiProxy']->requestPhpCgi($request, $GLOBALS['WWW_DIR'], $name,['SERVER_NAME' => $GLOBALS['MY_HOST'], 'SERVER_PORT' => '80', 'HTTP_HOST' => $GLOBALS['MY_HOST']],['debug_show_cgi_params' => false, 'readWriteTimeout' => 15000]);
}
use RingCentral\Psr7\Response;
function static_run($uri): Response{
$file_dir = $GLOBALS['WWW_DIR'].$uri; #完整文件路径
$file_dir = explode("?", $file_dir)[0]; #去掉动态路径
if(is_dir($file_dir)) $file_dir .= '/index.html';# 可以这里定义目录的默认索引页
$handle   = fopen($file_dir, "r");
$contents = fread($handle, filesize($file_dir));
fclose($handle);
return new Response(200, ['Content-Type'  => $GLOBALS['fcPhpCgiProxy']->getMimeType($file_dir),'Cache-Control' => "max-age=8640000",'Accept-Ranges' => 'bytes'], $contents);
}
 
function clearFcHost($request,$context){
$uri  = $request->getAttribute("requestURI");
$uri  = str_replace("/2016-08-15/proxy/".$context['service']['name']."/".$context['function']['name'],"",$uri);
$request = $request->withAttribute("requestURI", $uri);
return $request;
}
 

D、配置自定义域名
如图:
ServerLess实战:函数计算+NAS搭建无服务器thinkphp5

3、NAS配置详解
在对应目录上传代码包,点击下载,解压缩代码即可
4、测试访问
你的域名直接访问
你的域名/index.php?s=index/index/index
你的域名/about

都没问题的话就大功告成