You need to enable JavaScript to run this app. 使用Nginx server block部署Laravel时访问站点自动下载index.php的问题解决
优惠活动
大模型
产品
解决方案
定价
更多

使用Nginx server block部署Laravel时访问站点自动下载index.php的问题解决

问题根因

你当前的配置出现自动下载文件的问题,核心原因有两点:

  • 完全缺失PHP脚本解析的核心配置,Nginx没有调用php-fpm服务执行index.php,反而将其作为静态资源直接返回给客户端,浏览器识别到无法解析这类文件就触发了下载流程
  • 存在几处配置语法和逻辑错误,即使补全PHP解析规则,Laravel的单入口路由机制也无法正常工作
需要修正的具体配置点
  • 新增PHP脚本处理的location块,将所有.php结尾的请求转发给本地php-fpm服务解析执行
  • 修正www.example.com server块中IPv6监听的配置错误:原配置listen [::]:443;漏写了ssl参数,会导致IPv6网络环境下HTTPS握手失败
  • 重写try_files逻辑:将所有不存在的静态资源请求统一转发给Laravel入口index.php,保障Laravel路由能正常接管所有非静态资源请求
  • 调整index指令的排序,优先匹配Laravel入口文件index.php,避免误匹配目录下的其他静态首页文件
修正后的完整可用配置
# 非www域名强制跳转至www域名的HTTPS配置
server {
    server_name example.com;
    listen 443 ssl;
    listen [::]:443 ssl;
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    return 301 https://www.example.com$request_uri;
}

# Laravel站点核心配置
server {
    server_name www.example.com;
    listen 443 ssl;
    listen [::]:443 ssl; # 修正原配置漏写的ssl参数
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    include /etc/letsencrypt/options-ssl-nginx.conf;
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;

    root /var/www/example.com/public;
    # 优先匹配Laravel入口文件
    index index.php index.html index.htm;

    location / {
        # 所有不存在的资源请求统一转发给index.php,交由Laravel路由处理
        try_files $uri $uri/ /index.php?$query_string;
    }

    # 新增PHP解析块,将PHP请求转发给php-fpm处理
    location ~ \.php$ {
        # 注意:此处sock路径需要和本地安装的PHP版本匹配,常见路径如/run/php/php8.2-fpm.sock
        # 若php-fpm采用TCP监听模式,可替换为 fastcgi_pass 127.0.0.1:9000;
        fastcgi_pass unix:/run/php/php8.1-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    # 可选配置:屏蔽对隐藏敏感文件的直接访问(如.env)
    location ~ /\.(?!well-known).* {
        deny all;
    }
}
配置生效步骤
  • 先执行nginx -t检查配置语法,确认无报错后再继续
  • 执行systemctl reload nginx重载服务使配置生效
  • 确认Laravel项目下storage、bootstrap/cache目录的读写权限分配给Nginx运行用户(通常为www-data),否则会触发权限报错

提示:如果配置生效后出现502错误,优先检查php-fpm服务是否正常运行,以及配置中填写的sock/端口路径是否和本地实际环境匹配。


内容的提问来源于stack exchange,提问作者GTS Joe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.22 18:54:06