有人可以推荐一个最佳实践 nginx 配置来在单个域上运行多个 React 应用程序吗?这些应用程序将从不同的根目录提供服务。
因此 app1 和 app2 在 www.domain.com 上运行并获得服务:
www.domain.com/app1
www.domain.com/app2
App1 服务来自 /tmp1/app1
App2 服务来自 /tmp2/app2
最佳答案
我不是 react 应用程序的专家,但这里有一些简单的方法可以做到这一点。
在这两种情况下,请确保您的应用程序了解它是从子文件夹提供的,因此您需要为所有请求添加 /app1/
或 /app2/
前缀>.
选项 1:
这个示例只是提供静态文件的最简单的可能配置。
server {
server_name www.domain.com;
# Serve files for different applications from different paths
# Matched location will automatically search files under /tmp1
# For example request "GET /app1/index.html" returns file /tmp1/app1/index.html
location /app1 {
root /tmp1;
}
location /app2 {
root /tmp2;
}
}
您只需确保文件夹名称与请求中的子文件夹名称匹配即可。
选项 2:
执行此操作的其他方法是将子文件夹后的请求与 regex
匹配并使用 try_files
。这样你的根文件夹路径可以是任何路径。
# Serve files from subfolders using regex
# This comes with additional bonus of matching all requests to the index.html which is usually prefered for react apps
server {
server_name www.domain.com;
# Now your root can be anywhere and it doesn't need to contain folder 'app1'
location /app1/(.*) {
root /tmp1/app1;
try_files $1 index.html;
}
location /app2/(.*) {
root /tmp2/app2;
try_files $1 index.html;
}
}
关于reactjs - 使用 Nginx 在单个域上运行多个 React 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45265570/