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

Laravel部署至服务器后路由失效,页面无法访问求助

这种情况我部署Laravel时也碰到过好几次,大概率是服务器配置或者环境细节没到位,咱们一步步排查:

1. 先确认Web服务器的根目录与重写配置

这是最容易踩坑的点,Laravel的入口文件在public目录下,服务器必须把根目录指向这个文件夹,而不是项目的根目录!

如果用Apache:

  • 先启用URL重写模块:
    sudo a2enmod rewrite
    sudo systemctl restart apache2
    
  • 修改Apache的虚拟主机配置(比如/etc/apache2/sites-available/your-site.conf),确保public目录的AllowOverride设置为All,让.htaccess生效:
    <VirtualHost *:80>
        ServerName your-domain.com
        DocumentRoot /var/html/farhan/project/public
    
        <Directory /var/html/farhan/project/public>
            AllowOverride All
            Require all granted
        </Directory>
    </VirtualHost>
    
    配置完重启Apache生效。

如果用Nginx:

  • 检查站点配置文件(比如/etc/nginx/sites-available/your-site),确保root指向public目录,并且有正确的try_files规则转发请求到index.php:
    server {
        listen 80;
        server_name your-domain.com;
        root /var/html/farhan/project/public;
    
        index index.php index.html;
    
        location / {
            try_files $uri $uri/ /index.php?$query_string;
        }
    
        location ~ \.php$ {
            fastcgi_pass unix:/run/php/php8.2-fpm.sock; # 根据你的PHP版本调整路径
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
            include fastcgi_params;
        }
    }
    
    配置完重启Nginx:sudo systemctl restart nginx

2. 修复目录权限问题

Laravel需要对storage和bootstrap/cache目录有写入权限,不然缓存、日志生成失败会导致整个应用异常:

cd /var/html/farhan/project
sudo chown -R www-data:www-data storage bootstrap/cache
sudo chmod -R 775 storage bootstrap/cache

(如果你的服务器用Nginx,可能需要把www-data换成nginx,根据实际运行用户调整)

3. 调整.env配置与清除缓存

  • 打开/var/html/farhan/project/.env,确保APP_URL设置为你的服务器域名或IP,比如APP_URL=http://your-server-ip;如果是调试阶段,可以把APP_DEBUG=true打开,方便看到具体错误。
  • 部署后本地缓存和服务器环境不匹配,必须清除缓存:
    php artisan cache:clear
    php artisan config:clear
    php artisan route:clear
    php artisan view:clear
    
    生产环境下,确认配置正确后可以重新生成缓存:php artisan config:cache && php artisan route:cache

4. 检查PHP版本与依赖

  • 运行php -v确认服务器PHP版本符合你Laravel项目的要求(比如Laravel 10需要PHP 8.1+),版本不够的话需要升级PHP。
  • 如果是刚部署的项目,确保已经在服务器上安装了依赖:
    composer install --no-dev
    

如果做完以上步骤还是有问题,打开APP_DEBUG=true访问页面,看具体的错误提示——比如是不是数据库连接失败、缺少扩展(比如mbstring、xml这些Laravel必需的扩展),针对性解决就行。

内容的提问来源于stack exchange,提问作者Farhan Anees

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:38:44