大网数据广告活动
服务器运维问答

Serving a ReactJS app using nginx via a directory

· 52CE 我爱测

I've got a ReactJS app which works fine if served from the root of a subdirectory using the following code: server { listen 80; server_name sub.domain.net; root /var/www/vhosts/sub.domain.net/httpdocs; location / { try_files $uri…

问题原文

原帖链接 · kinabalu · CC BY-SA 3.0

I've got a ReactJS app which works fine if served from the root of a subdirectory using the following code:

server {

   listen  80;

   server_name sub.domain.net;

   root /var/www/vhosts/sub.domain.net/httpdocs;

   location / {
      try_files $uri $uri/ /index.html;
   }
}

However I'd like to serve this from the main domain.net instead, and getting errors in all previous attempts. Here's what I have and it definitely does not work, the same ReactJS files are within a directory off of the root:

server {
  listen  80;
  server_name domain.net;

  root /var/www/vhosts/domain.net/httpdocs;

  location / {
      try_files $uri $uri/ /index.html;
  }

  location /reactapp {
      try_files $uri $uri/ /index.html;
  }
}

When using it in this manner, I'm getting an Uncaught SyntaxError: Unexpected token < and it's attempting to serve the stylesheet and likely the .js from the root rather than the directory.

The app is built using webpack, and does work perfectly fine off of a subdirectory. Thanks everyone!

社区高分解答

原帖链接 · Juan García · CC BY-SA 4.0

I was struggling with the same problem. Finally I was able to solve it using official documentation and a combination of answers:

Assumptions:

  • Your React App is based on create-react-app package (you are using react-router-dom).
  • You are using Nginx and the root path is being used by another service (or even another React/Gatsby App which is my case).
  • You want to deploy the React App on a subdirectory and be able to serve all statics of your React App from that subdirectory.

React App Changes:

Based on official documentation.

  1. Update your BrowserRouter by adding a basename. Example: <BrowserRouter history={history} basename="/webapp">.
  2. Specify a homepage on your package.json. Example: "homepage": "/webapp".
  3. If you are referencing a static file by its relative path, you should add the subdirectory to that reference. Example: src="/static/logo/logo.png" becomes src="/webapp/static/logo/logo.png".

Nginx Changes:

location ^~ /webapp {
   alias /var/www/myapp/build;
   try_files $uri $uri/ /webapp/index.html;
}

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-12-20)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0 / CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。