温馨提示×

Laravel在Debian如何配Nginx

小樊
41
2026-10-08 04:20:26
栏目: 智能运维

下面给你一个在 Debian 上用 Nginx 运行 Laravel 的标准、可落地配置流程(假设你用的是 Debian 11/12 + PHP 8.1/8.2 + Nginx)。


一、安装必要软件

sudo apt update
sudo apt install -y nginx php-fpm php-cli php-mysql php-mbstring php-xml php-curl php-zip php-gd unzip

如果你是 PHP 8.2:

sudo apt install -y php8.2-fpm

确认 PHP-FPM 已运行:

systemctl status php8.2-fpm

二、上传或部署 Laravel 项目

例如项目放在:

/var/www/laravel

设置权限(⚠️ 很重要):

sudo chown -R www-data:www-data /var/www/laravel
sudo chmod -R 755 /var/www/laravel
sudo chmod -R 775 /var/www/laravel/storage
sudo chmod -R 775 /var/www/laravel/bootstrap/cache

三、配置 Nginx 虚拟主机

新建配置文件:

sudo nano /etc/nginx/sites-available/laravel

✅ 推荐 Nginx 配置(Laravel 官方风格)

server {
    listen 80;
    server_name example.com;   # 改成你的域名或服务器IP

    root /var/www/laravel/public;
    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

四、启用站点

sudo ln -s /etc/nginx/sites-available/laravel /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

五、配置 .env 和 key

cd /var/www/laravel
cp .env.example .env
php artisan key:generate

六、设置 storage 软链接(如果你是上传文件)

php artisan storage:link

七、常见排错

1️⃣ 403 Forbidden

  • root 指向错误(必须是 public)
  • 权限不是 www-data

2️⃣ File not found

  • php-fpm.sock 路径错误
  • 检查:
ls /run/php/

3️⃣ 404 路由正常但 POST 报错

  • 检查 csrf
  • Nginx 没正确转发 try_files

八、HTTPS(可选但强烈建议)

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d example.com

如果你愿意,我可以:

  • ✅ 给你 PHP 8.3 + Debian 12 最新配置
  • ✅ 帮你配 Laravel + Redis / Queue
  • ✅ 给你 Docker + Nginx 方案

直接说你的环境即可。

0 踩