部署前需安装Web服务器(Nginx/Apache)、PHP环境、数据库(MySQL)、Composer,确保版本兼容(ThinkPHP 6.x建议PHP 7.4+、Nginx 1.18+)。
sudo yum install epel-release -y
sudo yum install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx
sudo yum install https://rpms.remirepo.net/enterprise/remi-release-7.rpm -y
sudo yum-config-manager --enable remi-php74
sudo yum install php php-cli php-fpm php-mysqlnd php-gd php-mbstring php-curl php-xml php-bcmath -y
sudo systemctl start php-fpm
sudo systemctl enable php-fpm
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/
sudo yum install mysql-server -y
sudo systemctl start mysqld
sudo systemctl enable mysqld
# 设置root密码(首次登录需修改)
sudo mysql_secure_installation
将本地ThinkPHP项目通过scp、rsync或Git克隆到服务器指定目录(如/var/www/html/your_project),确保public目录为Web访问根目录(避免直接暴露应用核心文件)。
# 示例:使用scp上传本地项目(替换为实际路径)
scp -r /local/path/to/thinkphp_project root@your_server_ip:/var/www/html/your_project
进入项目目录,运行composer install安装依赖(如框架核心、第三方库),并设置runtime目录(存储缓存、日志)的可写权限:
cd /var/www/html/your_project
composer install --no-dev --optimize-autoloader # 生产环境关闭开发依赖
sudo chown -R nginx:nginx /var/www/html/your_project # 修改所有者(Nginx用户)
sudo chmod -R 755 /var/www/html/your_project/runtime # 设置runtime可写
编辑Nginx虚拟主机配置文件(如/etc/nginx/conf.d/thinkphp.conf),使请求指向public目录,并配置URL重写(让ThinkPHP处理动态路由):
server {
listen 80;
server_name your_domain.com; # 替换为域名或公网IP
root /var/www/html/your_project/public;
index index.php index.html;
# URL重写(隐藏index.php)
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# PHP处理
location ~ \.php$ {
fastcgi_pass unix:/run/php-fpm/www.sock; # PHP-FPM监听socket
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
# 禁止访问隐藏文件(如.htaccess)
location ~ /\. {
deny all;
}
}
启用配置并重启Nginx:
sudo ln -s /etc/nginx/conf.d/thinkphp.conf /etc/nginx/sites-enabled/ # 软链接到sites-enabled
sudo nginx -t # 测试配置语法
sudo systemctl restart nginx
编辑项目根目录下的.env文件(或config/database.php),填写数据库连接信息(确保数据库已创建):
DB_TYPE=mysql
DB_HOST=127.0.0.1
DB_NAME=your_database_name
DB_USER=your_database_user
DB_PASSWORD=your_database_password
DB_PORT=3306
DB_PREFIX=tp_ # 可选,表前缀
创建数据库及用户(若未创建):
# 登录MySQL
sudo mysql -u root -p
# 创建数据库
CREATE DATABASE your_database_name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
# 创建用户并授权
CREATE USER 'your_database_user'@'localhost' IDENTIFIED BY 'your_database_password';
GRANT ALL PRIVILEGES ON your_database_name.* TO 'your_database_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;
config/app.php,将app_debug设为false(避免泄露敏感信息):'app_debug' => false,
sudo yum install certbot python3-certbot-nginx -y
sudo certbot --nginx -d your_domain.com # 替换为域名
sudo systemctl restart nginx
config/cache.php使用Redis缓存。在浏览器输入http://your_domain.com(或HTTPS地址),若看到ThinkPHP欢迎页面,说明部署成功。若出现502错误,需检查:
sudo systemctl status php-fpm);fastcgi_pass路径是否正确(与PHP-FPM监听地址一致);runtime目录权限是否足够(755)。