我有一个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;
}
}
Run Code Online (Sandbox Code Playgroud)
当页面刷新时,上面会导致 404 错误。基于此链接,我修改了我的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;
}
}
Run Code Online (Sandbox Code Playgroud)
在上面它现在抛出错误,它找不到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
Run Code Online (Sandbox Code Playgroud)
dan*_*y74 14
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.
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅如何配置 nginx 以运行 angular4 应用程序
| 归档时间: |
|
| 查看次数: |
10649 次 |
| 最近记录: |