我有一个使用路由的angular 2
应用程序。当我打我的基本URL时,页面将正确加载并路由到下一页。但是,如果刷新同一页面,则会抛出404 error
。例如,如果我输入基本URL example.com
,则它路由到example.com/dashboard
,但是如果刷新此页面,则会导致404错误。
我的Nginx
配置设置文件中包含以下内容:
server {
ssl on;
ssl_certificate Certificate.cer;
ssl_certificate_key privateKey.key;
listen 443 ssl;
server_name example.com;
location / {
include proxy_params;
proxy_http_version 1.1;
proxy_buffering off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_pass http://localhost/temp/;
}
location /app {
include proxy_params;
proxy_http_version 1.1;
proxy_buffering off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_pass http://12.34.56.78:5001;
}
}
以上内容在刷新页面时导致404错误。基于this link,我修改了Nginx
配置,添加了try_files
部分,如下所示:
已更新:
server {
ssl on;
ssl_certificate Certificate.cer;
ssl_certificate_key privateKey.key;
listen 443 ssl;
server_name example.com;
location / {
include proxy_params;
proxy_http_version 1.1;
proxy_buffering off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_pass http://localhost/temp/;
alias /usr/share/nginx/html/proj1;
try_files $uri $uri/ /index.html$is_args$args;
}
location /app {
include proxy_params;
proxy_http_version 1.1;
proxy_buffering off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_pass http://12.34.56.78:5001;
}
}
上面,它现在抛出错误,找不到JS
文件。我在JS
中引用的所有index.html
文件(例如<script src="app.js"></script>
之类的文件)都与index.html
在同一目录中。
编辑:这是我在Chrome控制台的“网络”标签中看到的JS错误之一:
**General:**
Request URL: https://example.com/script.js
Request Method: GET
Status Code: 404 Not Found
Referrer Policy: no-referrer-when-downgrade
**Response Header:**
Connection: keep-alive
Content-Length: 571
Content-Type: text/html
Date:
Server: nginx/1.12.2
答案 0 :(得分:0)
Angular应用程序是单页应用程序(SPA)。这意味着您只提供一个HTML文件,即index.html
如果我刷新:
/ home = index.html
/ fred = index.html
/ any = index.html
因此,您需要让NGINX始终提供index.html,而不管路由如何。
例如:
server {
listen 8080;
server_name http://example.com;
root /path/to/your/dist/location;
# eg. root /home/admin/helloWorld/dist
index index.html index.htm;
location / {
try_files $uri $uri/ /index.html;
# This will allow you to refresh page in your angular app. Which will not give error 404.
}
}
答案 1 :(得分:0)
问题出在当您在例如http:/// some / path的路径中,而您单击刷新时会出现404错误页面。 ngnix配置中的这一额外行可以解决此问题。
server {
listen 8080;
server_name http://example.com;
root /path/to/your/dist/location;
index index.html index.htm;
location / {
try_files $uri $uri/ /index.html?/$request_uri;
# This will allow you to refresh page in your angular app.
}
}
添加后,重新启动nginx服务。