本範例說明如何使用網址重新導向功能,將所有傳入的要求重新導向至不同的主機或路徑。
相關內容
本頁面僅適用於傳統版應用程式負載平衡器。如果您在其他模式下使用負載平衡器,請參閱下列任一頁面:
如果您要設定 HTTP 至 HTTPS 的重新導向,請參閱「為傳統應用程式負載平衡器設定 HTTP 至 HTTPS 的重新導向」一文。
新增網址重新導向
主控台
- 前往 Google Cloud 控制台的負載平衡器清單。
前往「負載平衡」 - 如果負載平衡器類型為 HTTP(S) (傳統版),請按一下負載平衡器的名稱連結。
- 按一下「編輯」圖示 。
- 在「Host and path rules」中,選取「Advanced host and path rule (URL redirect, URL rewrite)」。
- 按一下 [Add host and path rule] (新增主機與路徑規則)。
- 在「Hosts」欄位中輸入 *。
- 按一下「 」。
- 在「動作」部分,選取「將用戶端重新導向至其他主機/路徑」。
- 針對主機重新導向,請輸入要重新導向的主機名稱,或省略以保留要求的主機。
- 在「Path redirect」(路徑重新導向) 中,選取「Full path redirect」(完整路徑重新導向)。
- 在「Path value」中,輸入要重新導向的路徑,或省略以保留要求的路徑。
- 在「Strip query」部分,按一下「Enable」。
- 按一下「儲存」,即可完成主機與路徑規則設定。
- 按一下「完成」,即可完成網址對應編輯作業。
- 按一下「更新」,完成負載平衡器的編輯作業。
gcloud
以下範例會傳回可設定的 3xx 回應碼,並使用適當的 URI 設定 Location
回應標頭,以及取代重新導向動作中所指定的主機和路徑。
使用
gcloud compute url-maps export
指令匯出現有的網址對應:gcloud compute url-maps export web-map-http \ --destination=lb-map-config.yaml \ --global
將下列內容新增至檔案結尾,即可更新網址對應檔案
lb-map-config.yaml
:hostRules: - hosts: - '*' pathMatcher: path-matcher-1 name: web-map-http pathMatchers: - defaultUrlRedirect: hostRedirect: NEW_HOSTNAME # Omit to keep the requested host httpsRedirect: false pathRedirect: /NEW_PATH # Omit to keep the requested path redirectResponseCode: MOVED_PERMANENTLY_DEFAULT stripQuery: true name: path-matcher-1
使用
gcloud compute url-maps import
指令更新網址對應:gcloud compute url-maps import web-map-http \ --global \ --source=lb-map-config.yaml