我想在我的域的子路由上托管一个演示应用程序。当我将应用程序放置在域的根目录并使用以下配置时,它会起作用:
server {
server_name domain.com www.domain.com;
root /var/www/my-app/build;
index index.html index.htm;
location / {
try_files $uri /index.html =404;
}
}
但是当我使用以下配置将其移动到子路由时,它会正确获取初始index.html,然后将静态文件请求(用于CSS,JS,图像...)也路由到index.html。 / p>
server {
listen 80;
server_name domain.com www.domain.com;
location / {
}
location /demo-apps/my-app{
root /var/www/my-app/build;
try_files $uri /index.html =404;
}
}
我不明白为什么。这是请求的屏幕截图,该请求成功,但返回js文件的index.html文件instad:
这是服务器上的文件夹结构:
据我了解,第一个屏幕截图中的请求应与第二个位置块中的$ uri条件匹配,并返回相应的js文件,但是显然,我错了。我需要进行哪些更改才能使其正常工作?
在有人问之前,是的,我确实重启了nginx。
答案 0 :(得分:1)
通过将root
的值与$uri
的值连接来构造文件的路径。因此,将在错误的位置/demo-apps/my-app/css/foo.css
查找对/var/www/my-app/build/demo-apps/my-app/css/foo.css
的请求。
您可以改为使用alias
(请参阅this document),例如:
location /demo-apps/my-app {
alias /var/www/my-app/build;
try_files $uri /demo-apps/my-app/index.html;
}
但是,同时使用alias
和try_files
可能会有问题。参见this long term issue。
或使用正则表达式location
(请参阅this dcoument)提取URI的后半部分,例如:
location ~ ^/demo-apps/my-app(/.*)?$ {
root /var/www/my-app/build;
try_files $1 /index.html =404;
}