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

Nginx配置Azure App Service部署Laravel 8项目出现404如何解决

部署Laravel 8到Nginx环境Azure App Service解决方案

此前修改server.php的操作无效,该文件仅为PHP内置开发服务器的入口,生产环境Nginx不会读取该文件。所有操作仅需通过FTPS完成,无需root权限或Azure后台操作权限。

1. 调整项目文件结构

先按照以下层级上传文件到FTP对应的/home/site目录下,没有对应目录直接新建即可:

/home/site
├── laravel/  # 存放Laravel核心代码(原项目除public外的所有文件)
│   ├── app/
│   ├── bootstrap/
│   ├── config/
│   ├── vendor/
│   ├── routes/
│   ├── .env
│   └── 其他非public目录文件
└── wwwroot/  # Nginx默认根目录,存放原Laravel public目录下的所有内容
    ├── index.php
    ├── favicon.ico
    ├── mix-manifest.json
    ├── css/
    ├── js/
    └── 其他public目录的静态资源

2. 修改路径引用配置

2.1 修改入口文件路径

编辑/home/site/wwwroot/index.php,调整两个核心加载路径:

  • 将原require __DIR__.'/../vendor/autoload.php';改为require __DIR__.'/../laravel/vendor/autoload.php';
  • 将原$app = require_once __DIR__.'/../bootstrap/app.php';改为$app = require_once __DIR__.'/../laravel/bootstrap/app.php';

2.2 绑定Laravel公共路径

编辑/home/site/laravel/app/Providers/AppServiceProvider.php,在register方法中添加公共路径绑定:

public function register()
{
    // 绑定public路径到实际的wwwroot目录
    $this->app->bind('path.public', function() {
        return realpath(base_path().'/../wwwroot');
    });
}

3. 添加Nginx自定义重写规则

默认Nginx配置没有适配Laravel的路由重写规则,需要手动上传自定义配置:

  1. 本地新建default.conf文件,写入以下配置(注意PHP版本要和你的服务端版本匹配,示例为PHP8.0,用7.4则把php8.0-fpm.sock改为php7.4-fpm.sock):
server {
    listen 8080;
    listen [::]:8080;
    root /home/site/wwwroot;
    index  index.php index.html index.htm;
    server_name  _;

    # Laravel路由重写规则
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        fastcgi_pass   unix:/run/php/php8.0-fpm.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include        fastcgi_params;
    }

    # 禁止访问隐藏敏感文件
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }
}
  1. 在FTPS的/home/site目录下新建nginx/conf.d层级目录,将上述default.conf上传到该目录下。

4. 适配环境配置

编辑/home/site/laravel/.env文件,调整以下配置项:

  • APP_URL填写你的站点实际域名
  • ASSET_URL填写你的站点实际域名,确保静态资源路径生成正确
  • 调试阶段可开启APP_DEBUG=true方便排查错误,上线后改为false
  • 其他数据库、缓存配置按实际环境填写

5. 重启应用生效

所有配置修改完成后,在FTPS的/home/site根目录下新建一个名为.restart的空文件,上传后Azure App Service会自动重启容器加载新配置。

常见问题排查

  • 仍返回404:先检查default.conf里的PHP-FPM socket路径是否和服务端PHP版本匹配,再确认wwwroot/index.php里的加载路径没有拼写错误
  • 权限报错:给/home/site/laravel/storage和/home/site/laravel/bootstrap/cache目录设置755权限,可通过FTP客户端右键修改目录权限实现

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 06:12:01