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

Ubuntu服务器Nginx+Docker Nginx部署React与Laravel API遇404问题

解决api.domain.com访问404问题

问题概述

在Ubuntu 20.04 LTS服务器上,系统Nginx部署React前端(domain.com访问正常),Docker容器内的Nginx部署Laravel+MySQL后端API,访问子域名api.domain.com时出现404错误,已为前后端创建server block并完成sites-enabled目录符号链接配置。


解决方案

1. 修正系统Nginx的后端server block配置

当前系统Nginx的后端配置直接指向本地/var/www/public目录,但Laravel代码实际挂载在Docker容器内,系统Nginx无法访问该路径,导致404。应将api.domain.com的请求反向代理到Docker内的Nginx服务端口:

修改后端server block配置为:

server {
    listen 80;
    server_name api.domain.com www.api.domain.com;

    location / {
        proxy_pass http://localhost:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

重启系统Nginx生效:

sudo systemctl restart nginx

2. 配置Docker内的Nginx正确处理Laravel请求

之前docker-compose中Nginx的配置被注释,需启用并配置正确的server block:

  1. 在项目本地目录创建nginx/conf.d/app.conf文件,内容如下:
server {
    listen 80;
    index index.php index.html;
    root /var/www/public;
    server_name localhost;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_pass app:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
    }
}
  1. 修改docker-compose.yml中webserver服务的volumes配置,取消注释并修正路径:
volumes:
  - ./:/var/www
  - ./nginx/conf.d/app.conf:/etc/nginx/conf.d/default.conf
  1. 重启Docker服务:
docker-compose down && docker-compose up -d

3. 验证连通性

  • 检查Docker容器状态:
docker ps

确保app和webserver容器处于Up状态。

  • 测试本地到Docker Nginx的连通性:
curl http://localhost:8000

应返回Laravel默认页面或API正常响应。

  • 验证Docker内部网络连通性:
docker exec -it webserver ping app

确保webserver容器能正常解析并连通app容器。

4. 确认DNS解析

使用以下命令验证api.domain.com是否正确解析到服务器公网IP:

nslookup api.domain.com

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 12:27:51