![](/img/trans.png)
[英]How to redirect all routes to index.html (Angular) in nest.js?
[英]How to redirect all Angular request to index.html in Nginx
我創建了一個簡單的 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;
}
}
並且一切正常。 because I'm using Angular UI Router , I'd like to forward all pages to index.html
so Angular will take over (so a request to example.com/users/new
will be redirect by Nginx to index.html
, for 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_files是正確使用的,正如Richard所示,您只需要在列表中添加index.html。 但是,沒有必要從最后刪除= 404,事實上,它最好不要。
location / {
try_files $uri $uri/ /index.html =404;
}
完成上述更改后,使用sudo nginx -s reload
配置
如果一切順利,最后一個從未使用過,路由只會嘗試文件,文件夾,角度應用程序。 就是這樣。 但是我認為最后讓= 404覆蓋所有基礎是一種好習慣。
無論你是否在try_files中使用= 404,通過將所有內容都指向index.html,你基本上都失去了從你的網絡服務器提供404錯誤的能力,除非index.html不存在(這是=404
進來的地方) 。 這意味着您需要在Angular JS中處理“未找到”URL和缺少頁面,並且您需要確定您使用的錯誤頁面將返回HTTP 200響應,而不是404.(這是因為當你指向index.html時,你已經為用戶提供了一個頁面,因此200)。
為了增加對上述內容的保證,google try_files angular js,您會發現大多數示例包含= 404。
參考文獻:
location / {
try_files $uri$args $uri$args/ index.html;
}
這對我有用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.