Linux服务器上 Laravel 配置全流程
一 环境准备与版本要求
sudo apt install php-fpm php-cli php-mysql php-curl php-gd php-mbstring php-xml php-zip git composer;CentOS 7 可启用 EPEL/Remi 仓库后安装对应 PHP 8.2 及扩展。确保与 Nginx/Apache 配套的 PHP-FPM 已安装并运行。二 部署代码与基础配置
composer install --optimize-autoloader --no-dev(生产环境跳过 dev 依赖)。.env.example 为 .env,配置关键项:
APP_ENV=production、APP_DEBUG=false、APP_URL=https://yourdomain.comDB_HOST=localhost、DB_DATABASE=...、DB_USERNAME=...、DB_PASSWORD=...php artisan key:generatechown -R www-data:www-data storage bootstrap/cache; chmod -R 775 storage bootstrap/cache)。三 Web 服务器配置
server {
listen 80;
listen [::]:80;
server_name example.com;
root /srv/example.com/public;
index index.php;
charset utf-8;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-Content-Type-Options "nosniff";
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
error_page 404 /index.php;
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.2-fpm.sock; # 按实际 PHP 版本与路径调整
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
}
启用站点:sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ && sudo nginx -t && sudo systemctl reload nginx。DocumentRoot 指向 /path/to/laravel/public,<Directory> 中开启 AllowOverride All,并确保启用 mod_rewrite。四 数据库与队列等生产必备
php artisan migrate --forcephp artisan db:seed --force* * * * * cd /var/www/your-project && php artisan schedule:run >> /dev/null 2>&1php artisan queue:work --queue=default --tries=3五 性能与安全优化
php artisan config:cachephp artisan route:cachephp artisan event:cache、php artisan view:cachephp artisan optimize:clearconfig:cache 后,框架不再加载 .env,请确保仅通过配置文件访问环境变量,避免 env() 在生产读取失败。bootstrap/app 中自定义为 /status,用于 LB/K8s 健康探测。