如何在Nginx中将所有Angular请求重定向到index.html

Wag*_*sUK 12 javascript nginx angularjs

我已经创建了一个简单的Nginx配置文件来为Angular服务器,如下所示:

server {
  listen 80;
  listen [::]:80;

  root /path/to/apps/myapp/current/dist;
  access_log /path/to/apps/myapp/current/log/nginx.access.log;
  error_log /path/to/apps/myapp/current/log/nginx.error.log info;

  index index.html;

  location ^~ /assets/ {
    gzip_static on;
    expires max;
    add_header Cache-Control public;
  }

  location / {
    try_files $uri $uri/ =404;
  }
}
Run Code Online (Sandbox Code Playgroud)

所有工作都按预期正常.因为我正在使用Angular UI路由器,所以我想转发所有页面,index.html以便Angular接管(因此请求example.com/users/new将由Nginx重定向index.html,以便Angular UI处理它)用于页面重新加载,链接等.

我怎样才能做到这一点?

我一直在玩这样的选项:

server {
    #implemented by default, change if you need different ip or port
    #listen *:80 | *:8000;
    server_name test.com;
    return 301 $scheme://www.test.com$request_uri;
}
Run Code Online (Sandbox Code Playgroud)

答案所述.但根据所有要求,我无法做任何类似工作.

建议将不胜感激.

Ric*_*ith 15

您需要将路由器添加到try_files指令的末尾,如下所示:

location / {
    try_files $uri $uri/ /index.html;
}
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请参阅此文


red*_*x05 10

您已经快知道了。如Richard所示,try_files是正确的选择,您只需要在列表中添加index.html。但是,没有必要从最后删除= 404,实际上最好不要删除。

location / {
    try_files $uri $uri/ /index.html =404;
}
Run Code Online (Sandbox Code Playgroud)

实施上述更改后,请使用 sudo nginx -s reload

  • $ uri将尝试将该请求作为文件,如果失败,它将移至下一个请求。
  • $ uri /将尝试将该请求作为文件夹/index.html进行尝试,然后将所有请求发送到index.html,您的角度应用程序将可以在该路由中进行路由(还请确保使用html5mode以避免使用#在网址中。
  • = 404将是您的最后一个后备,基本上是这样说的:我已经尝试过将其作为文件,文件夹并通过index.html进行尝试。如果index.html由于任何原因失败/不存在,我们将提供404错误。

为什么= 404?

如果一切顺利,则永远不会使用最后一个,而路由将仅尝试文件,文件夹,角度应用程序。就是这样。但是我认为将= 404覆盖所有基数是一种好习惯。

关于index.html catchall的重要说明

不管您是否在try_files中使用= 404,通过将所有内容都定向到index.html,除非index.html不存在(该目录确实存在),否则您基本上会失去从Web服务器提供404错误的能力=404。这意味着您将需要处理Angular JS中的“未找到” URL和缺少页面,并且您需要确定所使用的错误页面将返回HTTP 200响应而不是404。(这是因为指向index.html的那一刻,您已经为用户提供了一个页面,即200)。

为了使上述内容更加放心,google try_files angular js,您会发现大多数示例都包含= 404。

参考文献: