我有一个 angular 2
使用路由的应用程序。当我点击我的基本 URL 时,页面会正确加载并路由到下一页。但是,如果我刷新同一页面,则会抛出 404 error
.例如,如果我输入我的基本网址,即 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
最佳答案
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.
}
}
见 How to config nginx to run angular4 application
关于angular - 刷新具有 Angular 2 路由的现有 url 时出现 Nginx 404 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51987032/