Nginx无法识别index.html?Hostinger VPS部署React+NodeJS遇404错误
问题描述
在Hostinger购买VPS部署应用,NodeJS服务器运行正常,但访问域名bushnaq.group时显示404 Not Found(属于配置中的fallback逻辑)。React构建产物存放在/root/bushnaq/client/dist路径下,包含index.html文件,推测Nginx无法识别该路径。
相关配置文件如下:
Nginx配置文件 bushnaq.group.conf
server { listen 80; server_name bushnaq.group; location / { root /bushnaq/client/dist; try_files $uri $uri/ /index.html =404; } }
NodeJS服务器代码 index.js
import express from "express"; import dbConnection from "./dbConnection.js"; import routes from "./routes.js"; import cors from "cors"; const app = express(); app.use(cors({ origin: "https://ashoshari.github.io/bushnaq-group/" })); const port = process.env.PORT || 8000; const host = process.env.HOST || "0.0.0.0"; // Middleware to parse JSON requests app.use(express.json()); app.get("/", (req, res) => { res.send("Hello World!"); }); app.use("/api", routes); app.use((err, req, res, next) => { err.statusCode = err.statusCode || 500; err.message = err.message || "Internal Server Error"; res.status(err.statusCode).json({ message: err.message, }); }); // If database is connected successfully, then run the server dbConnection .getConnection() .then(() => { app.listen(port, host, () => { console.log(`Server is running on http://${host}:${port}`); }); }) .catch((err) => { console.log(`Failed to connect to the database: ${err.message}`); });
解决方案
1. 修正Nginx路径配置
你当前配置的root /bushnaq/client/dist是错误的绝对路径,实际React构建文件在/root/bushnaq/client/dist(root用户主目录下),需将Nginx配置中的root路径改为正确的绝对路径:
location / { root /root/bushnaq/client/dist; try_files $uri $uri/ /index.html =404; }
先通过命令验证路径有效性:
ls -l /root/bushnaq/client/dist/index.html
若输出文件详情,说明路径正确;若提示文件不存在,需确认构建文件的实际存放位置。
2. 解决Nginx权限问题
Nginx默认以www-data用户运行,/root目录对该用户通常无访问权限,可通过以下命令修改权限:
chown -R www-data:www-data /root/bushnaq/client/dist chmod -R 755 /root/bushnaq/client/dist
或者将构建文件夹移动到Nginx默认可访问的目录(如/var/www),再调整root路径。
3. 添加API反向代理规则
当前Nginx仅处理静态文件,你的NodeJS服务器在8000端口提供/api接口,需添加反向代理规则避免/api请求被当作静态文件处理:
server { listen 80; server_name bushnaq.group; location / { root /root/bushnaq/client/dist; try_files $uri $uri/ /index.html =404; } location /api { 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; } }
4. 验证配置并重启Nginx
修改配置后先验证合法性:
nginx -t
若提示test is successful,重启Nginx服务:
systemctl restart nginx
5. 开放端口
确保VPS的80端口已在防火墙中开放,Hostinger VPS可通过命令开放:
ufw allow 80/tcp
内容的提问来源于stack exchange,提问作者johnny shepherd
相关产品推荐
相关产品推荐

