问题原文
原帖链接 · 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-apppackage (you are usingreact-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.
- Update your
BrowserRouterby adding abasename. Example:<BrowserRouter history={history} basename="/webapp">. - Specify a
homepageon yourpackage.json. Example:"homepage": "/webapp". - 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"becomessrc="/webapp/static/logo/logo.png".
Nginx Changes:
location ^~ /webapp {
alias /var/www/myapp/build;
try_files $uri $uri/ /webapp/index.html;
}
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
