我创建了一个简单的 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;
}
}
一切都按预期正常工作。因为我正在使用Angular UI 路由器 https://github.com/angular-ui/ui-router,我想将所有页面转发到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;
}
如指定this https://stackoverflow.com/questions/10294481/how-to-redirect-a-url-in-nginx回答。但我无法根据所有要求进行类似的工作。
如有建议,我们将不胜感激。
你已经快明白了。 try_files 是正确的使用方法,正如 Richard 所示,您只需将 index.html 添加到列表中即可。不过,没有必要去掉末尾的=404,事实上,最好不要去掉。
location / {
try_files $uri $uri/ /index.html =404;
}
实施上述更改后,重新加载配置sudo nginx -s reload
- $uri将尝试将请求作为文件,如果失败,它将移动到
下一个。
-
$uri/将尝试将请求作为文件夹 /index.html 将
然后尝试,它将所有请求发送到您的index.html,其中您的
角度应用程序将能够路由事物(还要确保您使用
html5mode 避免在 url 中使用#。
-
=404将是你最后的后备,基本上是说:我已经尝试过将其作为文件、文件夹和通过index.html。如果index.html失败/没有
无论出于何种原因存在,我们都会提供 404 错误。
为什么=404?
如果一切顺利,最后一个永远不会被使用,路由只会尝试文件、文件夹、角度应用程序。就这样了。但我认为最后加上 =404 来涵盖所有基础是一个很好的做法。
关于index.html catchall 的重要说明
无论您是否在 try_files 中使用=404,通过将所有内容都定向到index.html,您基本上失去了从网络服务器提供404错误的能力,除非index.html不存在(这是在哪里)=404
进来)。这意味着您需要在 Angular JS 中处理“未找到”url 和缺失页面,并且您需要接受这样一个事实:您使用的错误页面将返回 HTTP 200 响应,而不是 404。(这是因为当您定向到index.html 时,您就已经向用户提供了一个页面,因此为200)。
为了对上述内容更加放心,请谷歌 try_files Angular js,您会发现大多数示例都包含 =404。
参考:
- http://nginx.org/en/docs/beginners_guide.html#control http://nginx.org/en/docs/beginners_guide.html#control
-
http://ajbogh.blogspot.ca/2015/05/setting-up-angularjs-html5-mode-in.html http://ajbogh.blogspot.ca/2015/05/setting-up-angularjs-html5-mode-in.html(仅举一例)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)