Nginx and SPAs (Angular)



我对nginx有以下配置:

server {
listen       80;
server_name  localhost;
location  /app {
root   /usr/share/nginx/html;
index  index.html index.htm;
try_files $uri /index.html;
}
}

运行容器并转到http://localhost:8000/app时它工作得很好,但如果我导航到一些子路由,例如:http://localhost:8000/app/products(这是anuglar路由器中的一个有效路由(,然后重新启动,我会得到nginx 404错误。

我想我的nginx配置有问题。任何帮助都将不胜感激。

尝试将try_files行更改为try_files $uri $uri/ /index.html?$args;

该指令检查是否存在按指定顺序排列的文件,并使用第一个找到的文件进行请求处理。

如果没有找到任何文件,则会对最后一个参数中指定的uri进行内部重定向。这应该是你的SPA应用程序路线。

这个终于对我有用了:try_files $uri $uri/ /app/index.html?$args;

我遇到了一个类似的问题,我在Nginx配置中添加了try_files$uri$uri//app/index.html,但它没有按预期工作。我还尝试了try_files$uri$uri//app/index.html$args;,但它仍然没有解决问题。经过进一步调查,我发现我正在修改/etc/nginx/nginx.conf文件,而nginx实际上正在从/etc/nginx/conf.d/default.conf中读取配置。对于任何面临相同问题的人,我提供了以下工作配置:

server {
listen       80;
listen  [::]:80;
server_name  localhost;
#access_log  /var/log/nginx/host.access.log  main;
location / {
root   /usr/share/nginx/html;
index  index.html index.htm;
try_files $uri $uri/ /index.html;
}
#error_page  404              /404.html;
# redirect server error pages to the static page /50x.html
#
error_page   500 502 503 504  /50x.html;
location = /50x.html {
root   /usr/share/nginx/html;
}
}

我在Docker容器中使用Nginx作为Angular应用程序的web服务器。

最新更新