Linux 上搭建 Laravel 服务器环境
一 准备与版本选择
php -v 与 php -m 检查版本与扩展。二 Ubuntu 或 Debian 搭建步骤
sudo apt update && sudo apt install nginx mysql-server php-fpm php-mysql php-mbstring php-xml php-curl php-zip php-gd php-bcmathsudo apt update && sudo apt install apache2 mysql-server libapache2-mod-php php-mysql php-mbstring php-xml php-curl php-zip php-gd php-bcmathcurl -sS https://getcomposer.org/installer | phpsudo mv composer.phar /usr/local/bin/composercomposer create-project --prefer-dist laravel/laravel my_laravelcd my_laravelcp .env.example .envphp artisan key:generate.env 配置数据库等敏感信息server {
listen 80;
server_name your_domain_or_ip;
root /var/www/my_laravel/public;
index index.php index.html;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; # 按实际 PHP 版本调整
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
}
sudo ln -s /etc/nginx/sites-available/laravel /etc/nginx/sites-enabledsudo nginx -t && sudo systemctl reload nginxmod_rewrite,虚拟主机 DocumentRoot 指向 /public,且 <Directory> 中 AllowOverride All。三 CentOS 或 RHEL 搭建步骤
sudo yum install epel-release -ysudo yum install https://rpms.remirepo.net/enterprise/remi-release-8.rpm -ysudo dnf module reset php -y && sudo dnf module enable php:remi-81 -ysudo yum install nginx mysql-server php php-fpm php-mysqlnd php-mbstring php-xml php-curl php-zip php-gd php-bcmath -ysudo systemctl enable --now nginx php-fpm mysqldphp artisan key:generatefastcgi_pass unix:/var/run/php-fpm/www.sock;fastcgi_pass 127.0.0.1:9000;(需确保 php-fpm 监听 9000)try_files 与安全头配置与上文 Nginx 示例一致sudo firewall-cmd --permanent --add-service=httpsudo firewall-cmd --reload四 数据库与权限安全
sudo mysql_secure_installationCREATE DATABASE laravel_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;CREATE USER 'laravel_user'@'localhost' IDENTIFIED BY 'StrongPassword!';GRANT ALL PRIVILEGES ON laravel_db.* TO 'laravel_user'@'localhost';FLUSH PRIVILEGES;.env 中设置:DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=laravel_user
DB_PASSWORD=StrongPassword!
sudo chown -R www-data:www-data /var/www/my_laravel/storage /var/www/my_laravel/bootstrap/cachesudo chmod -R 775 /var/www/my_laravel/storage /var/www/my_laravel/bootstrap/cachephp artisan config:cache、php artisan route:cache、php artisan view:cache五 验证与常见问题
php artisan serve,但生产环境请使用 Nginx/Apache/var/log/nginx/error.log/var/log/php-fpm.log 或 /var/log/php8.1-fpm.logstorage/logs/laravel.log.env 配置、APP_KEY、storage/bootstrap/cache 权限、PHP 错误日志try_files $uri $uri/ /index.php?$query_string; 与 root 指向 /public.env 中 DB_HOST/DB_PORT/DB_USERNAME/DB_PASSWORD 与数据库是否允许该用户远程/本地访问