簡體   English   中英

如何將所有 Angular 請求重定向到 Nginx 中的 index.html

[英]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指令的末尾,如下所示:

location / {
    try_files $uri $uri/ /index.html;
}

有關更多信息,請參閱此文

你差不多了。 try_files是正確使用的,正如Richard所示,您只需要在列表中添加index.html。 但是,沒有必要從最后刪除= 404,事實上,它最好不要。

location / {
    try_files $uri $uri/ /index.html =404;
}

完成上述更改后,使用sudo nginx -s reload配置

  • $ uri會將請求作為文件進行嘗試,如果失敗,則移動到下一個文件。
  • $ uri /將嘗試請求作為文件夾/index.html然后將嘗試,它將所有請求發送到您的index.html您的角應用程序將能夠路由的東西(同時確保您使用html5mode以避免使用#在網址中。
  • = 404將是你的最后一個回退,基本上說:我已經嘗試過這個文件,文件夾,並通過index.html。 如果index.html因任何原因失敗/不存在,我們將提供404錯誤。

為什么= 404?

如果一切順利,最后一個從未使用過,路由只會嘗試文件,文件夾,角度應用程序。 就是這樣。 但是我認為最后讓= 404覆蓋所有基礎是一種好習慣。

關於index.html catchall的重要說明

無論你是否在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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM