瞭解如何從 Google App Engine 標準環境安全地提供靜態內容,例如 HTML 檔案、CSS 和圖片。
事前準備
如果您的網站使用自訂網域名稱,請按照操作說明將自訂網域新增至您的專案。
提供網頁
App Engine 可提供靜態內容,例如 HTML 頁面和圖片等媒體。靜態內容是指不會以 JSP 或 Servlet 執行的任何內容。
以下範例是一個顯示歡迎訊息的基本 HTML 頁面。
<!DOCTYPE html>
<html>
<head>
<title>The App Engine Blog</title>
</head>
<body>
<h1>Welcome to the App Engine Blog</h1>
<p>This is being served by App Engine!</p>
</body>
</html>
靜態檔案的放置位置
您必須將提供的靜態檔案放在應用程式的 webapp
目錄中。您可以使用資料夾,但請注意,所有檔案路徑和 URI 都會相對於 webapp
目錄。
選擇靜態檔案的位置後,您必須使用 <static-files>
元素,在 appengine-web.xml
檔案中定義檔案位置。
在下方範例中,基本 appengine-web.xml
設定會將 webapp
目錄中的所有 HTML 檔案視為靜態檔案。
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<threadsafe>true</threadsafe>
<runtime>java8</runtime>
<static-files>
<include path="/**.html" >
</include>
</static-files>
</appengine-web-app>
您可以有多個 <include path>
元素,參照不同的目錄和不同檔案類型。請展開上一個範例:
<static-files>
<include path="/**.html" >
</include>
<include path="/images/**.jpg" >
</include>
</static-files>
從現在起,webapp/images/
目錄中所有副檔名為 .jpg
的檔案都會視為靜態檔案。
在上例中,如果我們想顯示 webapp/images
目錄中的 logo.jpg
,<img>
標記就會包含來源 URI <img src="/images/logo.jpg">
。
強制所有靜態內容採用 HTTPS
雖然 App Engine 支援透過 HTTP 或 HTTPS 提供內容,但建議您使用 HTTPS。為了設定安全網址,您必須將 <security-constraint>
元素新增至專案的 web.xml
。以下是 <security-constraint>
範例:
<security-constraint>
<web-resource-collection>
<web-resource-name>blog</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
使用 <transport-guarantee>CONFIDENTIAL</transport-guarantee>
後,所有要求都會自動重新導向至靜態內容的 HTTPS URI。
部署至 App Engine
您可以透過 Maven 將應用程式部署至 App Engine。
請前往專案的根目錄,並輸入以下內容:
mvn package appengine:deploy -Dapp.deploy.projectId=PROJECT_ID
將 PROJECT_ID 替換為您的 Google Cloud 專案 ID。如果 pom.xml
檔案已指定專案 ID,您就不需要在執行的指令中加入 -Dapp.deploy.projectId
屬性。
請在 Maven 部署應用程式後輸入下列指令,以便在新的應用程式中自動開啟網路瀏覽器分頁:
gcloud app browse
後續步驟
您可以使用靜態檔案,透過 App Engine 提供圖片、階層式樣式表和靜態 HTML 內容。如要拓展相關知識,請參閱利用 HTML 表單處理使用者資料。