如何在Nginx中将所有Angular请求重定向到index.html [英] How to redirect all Angular request to index.html in Nginx

查看:382
本文介绍了如何在Nginx中将所有Angular请求重定向到index.html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have create a simple Nginx config file to server an Angular like so:

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;
  }
}

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

And all works fine as expected. because I'm using Angular UI Router, I'd like to forward all pages to index.html so Angular will take over (so a request to example.com/users/new will be redirect by Nginx to index.html, for Angular UI to handle it) for pages reloads, links, etc.

怎么能我实现了这个目标吗?

How can I achieve this?

我一直在玩这样的选项:

I've playing around with options like:

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;
}

这个答案。但根据所有请求,我无法做任何相似的工作。

As specified in this answer. But I couldn't anything similar to work based on all requests.

建议将不胜感激。

推荐答案

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

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

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

参见此文档了解更多信息。

这篇关于如何在Nginx中将所有Angular请求重定向到index.html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆