Javascript 如何将所有角度请求重定向到Nginx中的index.html
我已经创建了一个简单的Nginx配置文件,用于服务器,如下所示:Javascript 如何将所有角度请求重定向到Nginx中的index.html,javascript,angularjs,nginx,Javascript,Angularjs,Nginx,我已经创建了一个简单的Nginx配置文件,用于服务器,如下所示: 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; ind
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;
}
}
一切正常。因为我正在使用,所以我想将所有页面转发到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;
}
如回答中所述。但基于所有的请求,我不能做任何类似的工作
非常感谢您的建议。您需要将路由器添加到
try\u files
指令的末尾,如下所示:
location / {
try_files $uri $uri/ /index.html;
}
更多信息,请参阅 你就快拿到了。try_文件是正确使用的文件,正如Richard所示,您只需要将index.html添加到列表中。但是,没有必要从末尾删除=404,事实上,最好不要删除
location / {
try_files $uri $uri/ /index.html =404;
}
一旦实现了上述更改,请使用sudo nginx-s reload重新加载配置
- $uri将以文件的形式尝试请求,如果失败,它将移动到 下一个
- $uri/将作为文件夹/index.html尝试请求 然后重试,它会将所有请求发送到index.html,其中 angular应用程序将能够路由事物(同时确保您使用 避免在url中使用#的HTML5模式
- =404将是您最后的退路,基本上是说:我已经尝试将其作为文件、文件夹,并通过index.html来实现 无论出于何种原因存在,我们都将提供404错误
=404
的作用)。这意味着您需要处理Angular JS中的“Not Found”URL和缺少的页面,并且您需要接受这样一个事实,即您使用的错误页面将返回HTTP 200响应,而不是404响应。(这是因为当您指向index.html时,您已经向用户提供了一个页面,因此是200)
为了让你更加放心,google try_文件angular js,你会发现大多数例子都是include=404
参考文献:
- (仅举一例)