You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 5.6子目录部署Nginx跳转404问题排查求助

解决Laravel 5.6部署在Nginx子目录的404问题

嘿,我来帮你搞定这个Laravel部署在Nginx子目录的404问题!结合你给出的配置片段,这个问题大概率是Nginx的路由重写规则没适配子目录,再加上Laravel的环境配置没跟上导致的,咱们一步步来解决:

1. 先确认项目的实际路径

首先得明确:你的Laravel项目根目录是不是在/var/www/example/staging/project?如果是的话,咱们接下来的配置调整才能精准命中问题。

2. 修正Nginx的Server配置

你现有的配置里root /var/www/example没问题,但缺少针对/staging/project这个子目录的专属路由规则——毕竟Laravel是单入口应用,所有请求都得指向index.php才行。给你补全并修正后的配置片段:

server {
    listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server;
    server_name _;
    root /var/www/example;
    index index.php index.html index.htm;

    ssl_certificate "/etc/letsencrypt/live/example.com/fullchain.pem";
    ssl_certificate_key "/etc/letsencrypt/live/example.com/privkey.pem";
    # 这里可以保留你原本的SSL相关配置,比如ssl_protocols、ssl_ciphers这些

    # 静态资源直接返回,提升性能,不用走PHP处理
    location ~* ^/staging/project/(css|js|images|fonts)/ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        try_files $uri =404;
    }

    # 核心:适配子目录的Laravel路由重写
    location /staging/project {
        try_files $uri $uri/ /staging/project/index.php?$query_string;
    }

    # PHP-FPM处理规则,适配子目录的index.php
    location ~ \.php$ {
        # 这里要对应你的PHP-FPM地址,比如unix套接字或者TCP端口,注意PHP版本
        fastcgi_pass unix:/var/run/php/php7.2-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;

        # 关键:让Laravel识别到当前是HTTPS环境
        fastcgi_param HTTP_X_FORWARDED_PROTO https;
    }
}

3. 调整Laravel的环境配置

打开项目根目录下的.env文件,修改这两个参数:

APP_URL=https://example.com/staging/project
APP_ENV=staging

同时确认config/app.php里的url参数是从环境变量读取的(默认就是这样,但保险起见检查下):

'url' => env('APP_URL', 'http://localhost'),

4. 验证配置并重启Nginx

  • 先检查Nginx配置是否合法,避免语法错误:
sudo nginx -t
  • 如果输出test is successful,就重启Nginx让配置生效:
sudo systemctl restart nginx

最后踩坑提醒

  • 权限问题:Nginx运行用户(通常是www-data)需要能读取项目目录,且storage和bootstrap/cache目录需要写入权限,执行这两条命令搞定:
sudo chown -R www-data:www-data /var/www/example/staging/project/storage /var/www/example/staging/project/bootstrap/cache
sudo chmod -R 775 /var/www/example/staging/project/storage /var/www/example/staging/project/bootstrap/cache
  • 优先级问题:如果你的Nginx配置里还有其他location /规则,要确保/staging/project的规则放在前面——因为Nginx会优先匹配最具体的location规则。

这样调整后,访问https://example.com/staging/project/应该就能正常打开Laravel项目了。后续要部署多站点的话,要么在这个server块里添加对应子目录的location规则,要么新建独立的server块(如果是不同域名的话)就行。

内容的提问来源于stack exchange,提问作者Bhargav Mehta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:15:29