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

Laravel虚拟主机问题:访问http://first-app/时出现代码报错

解决Laravel虚拟主机访问时输出PHP代码的问题

你遇到的情况并非Laravel代码错误,而是Web服务器未正确配置PHP解析规则,导致PHP代码未被执行,直接以文本形式输出。以下是针对常见Web服务器的解决步骤:

Apache服务器配置修复

  • 检查PHP模块是否启用:执行命令 apache2ctl -M | grep php,若没有输出,需安装对应PHP版本并启用模块(例如 apt install php8.2 libapache2-mod-php8.2 && a2enmod php8.2)。
  • 修正虚拟主机配置:打开你的虚拟主机配置文件(通常路径为 /etc/apache2/sites-available/first-app.conf),确保以下配置正确:
    <VirtualHost *:80>
        ServerName first-app
        DocumentRoot /var/www/first-app/public
    
        <Directory /var/www/first-app/public>
            Options Indexes FollowSymLinks
            AllowOverride All
            Require all granted
    
            # 确保PHP文件被正确解析
            <FilesMatch \.php$>
                SetHandler application/x-httpd-php
            </FilesMatch>
        </Directory>
    
        ErrorLog ${APACHE_LOG_DIR}/first-app-error.log
        CustomLog ${APACHE_LOG_DIR}/first-app-access.log combined
    </VirtualHost>
    
  • 启用URL重写模块:执行 a2enmod rewrite,然后重启Apache服务:systemctl restart apache2。
  • 修复目录权限:确保Web服务器用户(通常为www-data)拥有项目存储目录的写入权限:
    chown -R www-data:www-data /var/www/first-app/storage /var/www/first-app/bootstrap/cache
    chmod -R 775 /var/www/first-app/storage /var/www/first-app/bootstrap/cache
    

Nginx服务器配置修复

  • 检查PHP-FPM状态:执行 systemctl status php8.2-fpm(根据你的PHP版本调整),确保服务正常运行,未安装则执行 apt install php8.2-fpm。
  • 修正虚拟主机配置:打开配置文件(通常路径为 /etc/nginx/sites-available/first-app),确保配置如下:
    server {
        listen 80;
        server_name first-app;
        root /var/www/first-app/public;
    
        index index.php index.html index.htm;
    
        # Laravel伪静态规则
        location / {
            try_files $uri $uri/ /index.php?$query_string;
        }
    
        # PHP解析规则
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/run/php/php8.2-fpm.sock; # 路径需匹配你的PHP-FPM版本
        }
    
        # 禁止访问.ht文件
        location ~ /\.ht {
            deny all;
        }
    }
    
  • 启用虚拟主机并重启Nginx:执行 ln -s /etc/nginx/sites-available/first-app /etc/nginx/sites-enabled/,测试配置 nginx -t,无错误则重启服务:systemctl restart nginx。
  • 同样执行Apache部分的目录权限修复命令。

通用排查项

  • 检查本地hosts文件:确保存在 127.0.0.1 first-app 的映射(Windows路径:C:\Windows\System32\drivers\etc\hosts;Linux/macOS路径:/etc/hosts)。
  • 验证默认索引:若访问 http://first-app/index.php 能正常显示Laravel页面,说明Web服务器未将index.php设为优先索引文件,需在配置的index指令中把index.php放在最前面。

内容的提问来源于stack exchange,提问作者Osama Nisar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 22:58:34