How to redirect all Angular request to index.html in Nginx

廉价感情. 提交于 2019-11-25 15:18:52

You need to add the router to the end of your try_files directive, like this:

location / {
    try_files $uri $uri/ /index.html;
}

See this document for more.

You've nearly got it. try_files is the correct one to use, as Richard shows, you just needed to add your index.html in the list. However, there is no need to remove the =404 from the end, in fact, its better not to.

location / {
    try_files $uri $uri/ /index.html =404;
}

Once the above change is implemented, reload the config with sudo nginx -s reload

  • $uri will try the request as a file, if this fails, it moves to the next one.
  • $uri/ will try the request as a folder /index.html will then be tried, which sends all requests to your index.html where your angular app will be able to route things (also make sure you use html5mode to avoid the use of # in the url.
  • =404 will be your final fallback, basically saying: I've tried this as a file, folder, and via index.html. If index.html fails/does not exist for whatever reason, we will serve a 404 error.

Why =404?

If all goes well, the last one is never used, and routing will just try file, folder, angular app. And that would be it. But I see it as good practice to have the =404 on the end to cover all bases.

Important note about index.html catchall

Regardless of whether or not you use the =404 in try_files, by directing everything to index.html, you basically lose the ability to serve 404 errors from your webserver, unless index.html does not exist (which is where =404 comes in). This means that you will need to handle 'Not Found' urls and missing pages within Angular JS, and you need to be ok with the fact that the error page you use will return a HTTP 200 response, rather than 404. (This is because the moment you direct to the index.html, you've served a page to the user, thus 200).

For added reassurance on the above, google try_files angular js and you will find most examples incorporate =404.

References:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!