Apache 配置:.htaccess

Apache .htaccess 檔案允許使用者配置他們控制的 Web 伺服器目錄,而無需修改主配置檔案。

雖然這很有用,但需要注意的是,使用 .htaccess 檔案會降低 Apache 的速度,因此,如果您可以訪問主伺服器配置檔案(通常稱為 httpd.conf),您應該將此邏輯新增到 Directory 塊中。

有關 .htaccess 檔案功能的更多詳細資訊,請參閱 Apache HTTPD 文件站點中的 .htaccess

本文件的其餘部分將討論您可以新增到 .htaccess 的不同配置選項及其作用。

以下大多數塊都使用 IfModule 指令,僅當相應模組配置正確且伺服器已載入時才執行塊內的指令。這樣,如果模組未載入,我們就可以避免伺服器崩潰。

重定向

有時我們需要告訴使用者資源已移動,無論是臨時移動還是永久移動。這就是我們使用 RedirectRedirectMatch 的原因。

apacheconf
<IfModule mod_alias.c>
  # Redirect to a URL on a different host
  Redirect "/service" "http://foo2.example.com/service"

  # Redirect to a URL on the same host
  Redirect "/one" "/two"

  # Equivalent redirect to URL on the same host
  Redirect temp "/one" "/two"

  # Permanent redirect to a URL on the same host
  Redirect permanent "/three" "/four"

  # Redirect to an external URL
  # Using regular expressions and RedirectMatch
  RedirectMatch "^/oldfile\.html/?$" "http://example.com/newfile.php"
</IfModule>

第一個引數的可能值如下所列。如果未包含第一個引數,則預設為 temp

permanent

返回永久重定向狀態 (301),表示資源已永久移動。

temp

返回臨時重定向狀態 (302)。這是預設值

seeother

返回“See Other”狀態 (303),表示資源已被替換。

gone

返回“Gone”狀態 (410),表示資源已被永久刪除。使用此狀態時,應省略 URL 引數。

跨域資源

第一組指令控制從伺服器訪問資源的 CORS(跨域資源共享)。CORS 是一種基於 HTTP 頭的機制,允許伺服器指示瀏覽器應允許載入資源的外部來源(域、協議或埠)。

出於安全原因,瀏覽器會限制從指令碼發起的跨域 HTTP 請求。例如,XMLHttpRequest 和 Fetch API 遵循同源策略。使用這些 API 的 Web 應用程式只能從載入該應用程式的同源請求資源,除非來自其他來源的響應包含適當的 CORS 頭。

通用 CORS 訪問

此指令將為目錄中來自任何網站的所有資源新增 CORS 頭。

apacheconf
<IfModule mod_headers.c>
  Header set Access-Control-Allow-Origin "*"
</IfModule>

除非您稍後在配置中或在設定此指令的下級目錄配置中覆蓋該指令,否則來自外部伺服器的每個請求都將被接受,這不太可能是您想要的。

另一種方法是明確說明哪些域可以訪問您網站的內容。在下面的示例中,我們將訪問許可權限制為我們主站點 (example.com) 的子域。這更安全,也可能是您想要做的。

apacheconf
<IfModule mod_headers.c>
  Header set Access-Control-Allow-Origin "subdomain.example.com"
</IfModule>

跨域影像

正如 Chromium 部落格 所報道並記錄在 允許跨域使用影像和畫布 中,可能會導致 指紋識別 攻擊。

為了減輕這些攻擊的可能性,您應該在請求的影像中使用 crossorigin 屬性,並在 .htaccess 中使用下面的程式碼片段來設定來自伺服器的 CORS 頭。

apacheconf
<IfModule mod_setenvif.c>
  <IfModule mod_headers.c>
    <FilesMatch "\.(bmp|cur|gif|ico|jpe?g|a?png|svgz?|webp|heic|heif|avif)$">
      SetEnvIf Origin ":" IS_CORS
      Header set Access-Control-Allow-Origin "*" env=*IS_CORS*
    </FilesMatch>
  </IfModule>
</IfModule>

Google Chrome 的 Google 字型故障排除指南 告訴我們,雖然 Google 字型可能會在每個響應中傳送 CORS 頭,但一些代理伺服器可能會在瀏覽器使用它來渲染字型之前將其剝離。

apacheconf
<IfModule mod_headers.c>
  <FilesMatch "\.(eot|otf|tt[cf]|woff2?)$">
    Header set Access-Control-Allow-Origin "*"
  </FilesMatch>
</IfModule>

跨域資源計時

資源計時 規範定義了一個介面,用於 Web 應用程式訪問文件中資源的完整計時資訊。

Timing-Allow-Origin 響應頭指定允許檢視透過資源計時 API 功能檢索的屬性值的源,否則這些屬性值會因跨域限制而被報告為零。

如果資源未附帶 Timing-Allow-Origin,或者在發出請求後標頭中未包含源,則 PerformanceResourceTiming 物件的某些屬性將設定為零。

apacheconf
<IfModule mod_headers.c>
  Header set Timing-Allow-Origin: "*"
</IfModule>

自定義錯誤頁面/訊息

Apache 允許您根據使用者收到的錯誤型別為他們提供自定義錯誤頁面。

錯誤頁面以 URL 形式呈現。這些 URL 可以以斜槓 (/) 開頭表示本地 Web 路徑(相對於 DocumentRoot),也可以是客戶端可以解析的完整 URL。

有關更多資訊,請參閱 HTTPD 文件站點上的 ErrorDocument 指令 文件。

apacheconf
ErrorDocument 500 /errors/500.html
ErrorDocument 404 /errors/400.html
ErrorDocument 401 https://example.com/subscription_info.html
ErrorDocument 403 "Sorry, can't allow you access today."

錯誤預防

此設定會影響 MultiViews 對其應用配置的目錄的工作方式。

MultiViews 的效果如下:如果伺服器收到對 /some/dir/foo 的請求,如果 /some/dir 啟用了 MultiViews,並且 /some/dir/foo 不存在,那麼伺服器將讀取目錄以查詢名為 foo.* 的檔案,並有效地偽造一個型別對映,該對映命名所有這些檔案,為其分配與客戶端按名稱請求其中一個檔案時相同的媒體型別和內容編碼。然後,它選擇最符合客戶端要求的匹配項。

此設定停用此配置所應用的目錄的 MultiViews,並防止 Apache 在同名目錄不存在時因重寫而返回 404 錯誤。

apacheconf
Options -MultiViews

媒體型別和字元編碼

Apache 使用 mod_mime 透過將 URI 或檔名中的模式對映到元資料值來為 HTTP 響應選擇的內容分配內容元資料。

例如,內容檔案的檔名副檔名通常定義內容的 Internet 媒體型別、語言、字元集和內容編碼。此資訊在包含該內容的 HTTP 訊息中傳送,並在選擇替代方案時用於內容協商,以便在選擇要服務的幾種可能內容之一時尊重使用者的偏好。

更改檔案的元資料不會更改 Last-Modified 標頭的值。因此,客戶端或代理可能仍會使用以前快取的副本,並帶有以前的標頭。如果您更改元資料(語言、內容型別、字元集或編碼),您可能需要“觸碰”受影響的檔案(更新其最後修改日期),以確保所有訪問者都收到更正的內容標頭。

使用適當的媒體型別(又稱 MIME 型別)提供資源

將媒體型別與一個或多個副檔名關聯,以確保資源將得到適當的服務。

伺服器應按照 HTML 規範 的指示,對 JavaScript 資源使用 text/javascript

apacheconf
<IfModule mod_mime.c>
  # Data interchange
    AddType application/atom+xml      atom
    AddType application/json          json map topojson
    AddType application/ld+json       jsonld
    AddType application/rss+xml       rss
    AddType application/geo+json      geojson
    AddType application/rdf+xml       rdf
    AddType application/xml           xml
  # JavaScript
    AddType text/javascript           js mjs
  # Manifest files
    AddType application/manifest+json     webmanifest
    AddType application/x-web-app-manifest+json         webapp
    AddType text/cache-manifest           appcache
  # Media files
    AddType audio/mp4                     f4a f4b m4a
    AddType audio/ogg                     oga ogg opus
    AddType image/bmp                     bmp
    AddType image/svg+xml                 svg svgz
    AddType image/webp                    webp
    AddType video/mp4                     f4v f4p m4v mp4
    AddType video/ogg                     ogv
    AddType video/webm                    webm
    AddType image/x-icon    cur ico
  # HEIF Images
    AddType image/heic                    heic
    AddType image/heif                    heif
  # HEIF Image Sequence
    AddType image/heics                   heics
    AddType image/heifs                   heifs
  # AVIF Images
    AddType image/avif                    avif
  # AVIF Image Sequence
    AddType image/avis                    avis
  # WebAssembly
    AddType application/wasm              wasm
  # Web fonts
    AddType font/woff                         woff
    AddType font/woff2                        woff2
    AddType application/vnd.ms-fontobject                eot
    AddType font/ttf                          ttf
    AddType font/collection                   ttc
    AddType font/otf                          otf
  # Other
    AddType application/octet-stream          safariextz
    AddType application/x-bb-appworld         bbaw
    AddType application/x-chrome-extension    crx
    AddType application/x-opera-extension     oex
    AddType application/x-xpinstall           xpi
    AddType text/calendar                     ics
    AddType text/markdown                     markdown md
    AddType text/vcard                        vcard vcf
    AddType text/vnd.rim.location.xloc        xloc
    AddType text/vtt                          vtt
    AddType text/x-component                  htc
</IfModule>

設定預設字元集屬性

網路上的每段內容都有一個字元集。大多數(如果不是全部)內容都是 UTF-8 Unicode。

使用 AddDefaultCharset 為所有標記為 text/htmltext/plain 的資源提供 UTF-8 字元集。

apacheconf
<IfModule mod_mime.c>
  AddDefaultCharset utf-8
</IfModule>

為特定媒體型別設定字元集

使用 mod_mime 中可用的 AddCharset 指令,提供以下檔案型別,並將 charset 引數設定為 UTF-8

apacheconf
<IfModule mod_mime.c>
  AddCharset utf-8 .appcache \
    .bbaw \
    .css \
    .htc \
    .ics \
    .js \
    .json \
    .manifest \
    .map \
    .markdown \
    .md \
    .mjs \
    .topojson \
    .vtt \
    .vcard \
    .vcf \
    .webmanifest \
    .xloc
</IfModule>

Mod_rewriteRewriteEngine 指令

mod_rewrite 提供了一種根據正則表示式規則動態修改傳入 URL 請求的方法。這允許您以您喜歡的任何方式將任意 URL 對映到您的內部 URL 結構。

它支援無限數量的規則以及每個規則無限數量的附加規則條件,以提供真正靈活而強大的 URL 操作機制。URL 操作可以依賴於各種測試:伺服器變數、環境變數、HTTP 頭、時間戳、外部資料庫查詢以及各種其他外部程式或處理程式,可以用於實現細粒度的 URL 匹配。

啟用 mod_rewrite

啟用 mod_rewrite 的基本模式是使用它的所有其他任務的先決條件。

所需步驟是

  1. 根據 RewriteEngine 文件,開啟重寫引擎(這對於 RewriteRule 指令的工作是必需的)
  2. 如果尚未啟用,請啟用 FollowSymLinks 選項。請參閱 核心選項 文件
  3. 如果您的 Web 主機不允許 FollowSymlinks 選項,您需要將其註釋掉或刪除,然後取消註釋 Options +SymLinksIfOwnerMatch 行,但請注意 效能影響
apacheconf
<IfModule mod_rewrite.c>
  RewriteEngine On
  Options +FollowSymlinks
  # Options +SymLinksIfOwnerMatch
  # RewriteBase /
  # RewriteOptions <options>
</IfModule>

強制 HTTPS

這些重寫規則將把 URL 的 http:// 不安全版本重定向到 https:// 安全版本,如 Apache HTTPD wiki 中所述。

apacheconf
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTPS} !=on
  RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
</IfModule>

如果您使用 cPanel AutoSSL 或 Let's Encrypt webroot 方法建立 TLS 證書,如果驗證請求被重定向到 HTTPS,則證書驗證將失敗。請開啟您需要的條件。

apacheconf
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTPS} !=on
  RewriteCond %{REQUEST_URI} !^/\.well-known/acme-challenge/
  RewriteCond %{REQUEST_URI} !^/\.well-known/cpanel-dcv/[\w-]+$
  RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9]{32}\.txt(?:\ Comodo\ DCV)?$
  RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>

www. URL 重定向

這些指令會將 www.example.com 重寫為 example.com

您不應在多個來源(有 www 和無 www)中複製內容。這可能會導致 SEO 問題(重複內容),因此,您應該選擇其中一個替代方案並重定向另一個。您還應該使用 規範 URL 來指示搜尋引擎應該抓取哪個 URL(如果它們支援此功能)。

設定 %{ENV:PROTO} 變數,以允許重寫自動重定向到適當的方案 (httphttps)。

該規則預設假定 HTTP 和 HTTPS 環境都可用於重定向。

apacheconf
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTPS} =on
  RewriteRule ^ - [E=PROTO:https]
  RewriteCond %{HTTPS} !=on
  RewriteRule ^ - [E=PROTO:http]

  RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
  RewriteRule ^ %{ENV:PROTO}://%1%{REQUEST_URI} [R=301,L]
</IfModule>

在 URL 開頭插入 www.

這些規則將在 URL 的開頭插入 www.。重要的是要注意,您絕不應該在兩個不同的 URL 下提供相同的內容。

這可能會導致 SEO 問題(重複內容),因此,您應該選擇其中一個替代方案並重定向另一個。對於支援它們的搜尋引擎,您應該使用 規範 URL 來指示搜尋引擎應該抓取哪個 URL。

設定 %{ENV:PROTO} 變數,以允許重寫自動重定向到適當的方案 (httphttps)。

該規則預設假定 HTTP 和 HTTPS 環境都可用於重定向。如果您的 TLS 證書無法處理重定向期間使用的其中一個域,則應開啟該條件。

如果您為網站的某些部分使用“真實”子域,則以下內容可能不是一個好主意。

apacheconf
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{HTTPS} =on
  RewriteRule ^ - [E=PROTO:https]
  RewriteCond %{HTTPS} !=on
  RewriteRule ^ - [E=PROTO:http]

  RewriteCond %{HTTPS} !=on

  RewriteCond %{HTTP_HOST} !^www\. [NC]
  RewriteCond %{SERVER_ADDR} !=127.0.0.1
  RewriteCond %{SERVER_ADDR} !=::1
  RewriteRule ^ %{ENV:PROTO}://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
</IfModule>

幀選項

以下示例傳送 X-Frame-Options 響應頭,值為 DENY,通知瀏覽器不要在任何幀中顯示網頁內容,以保護網站免受 點選劫持 的攻擊。

這可能不適合所有人。您應該閱讀有關 X-Frame-Options 頭部的其他兩個可能值 的資訊:SAMEORIGINALLOW-FROM

雖然您可以為網站的所有頁面傳送 X-Frame-Options 標頭,但這可能會帶來負面影響,因為它甚至會禁止框架化您的內容(例如:當用戶使用 Google 圖片搜尋結果頁面訪問您的網站時)。

儘管如此,您仍應確保為所有允許使用者執行狀態更改操作的頁面傳送 X-Frame-Options 標頭(例如:包含一鍵購買連結、結賬或銀行轉賬確認頁面、進行永久配置更改的頁面等)。

apacheconf
<IfModule mod_headers.c>
  Header always set X-Frame-Options "DENY" "expr=%{CONTENT_TYPE} =~ m#text/html#i"
</IfModule>

內容安全策略(CSP)

CSP (內容安全策略) 透過設定 Content Security Policy 來允許您網站信任的內容來源,從而降低跨站指令碼和其他內容注入攻擊的風險。

沒有適用於所有網站的策略,以下示例旨在作為您可以為您的網站修改的指南。

為了簡化 CSP 的實現,您可以使用線上 CSP 標頭生成器。您還應該使用 驗證器 來確保您的標頭按您希望的方式工作。

apacheconf
<IfModule mod_headers.c>
  Content-Security-Policy "default-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'; upgrade-insecure-requests" "expr=%{CONTENT_TYPE} =~ m#text\/(html|javascript)|application\/pdf|xml#i"
</IfModule>

目錄訪問

此指令將阻止訪問沒有伺服器配置使用的任何格式的索引檔案的目錄,例如 index.htmlindex.php

apacheconf
<IfModule mod_autoindex.c>
    Options -Indexes
</IfModule>

阻止訪問隱藏檔案和目錄

在 Macintosh 和 Linux 系統中,以句點開頭的檔案是隱藏的,但如果您知道它們的名稱和位置,則無法阻止訪問。這些型別的檔案通常包含使用者偏好設定或實用程式的保留狀態,並且可能包含相當私密的位置,例如 .git.svn 目錄。

.well-known/ 目錄代表“已知位置”的 標準 (RFC 5785) 路徑字首(例如:/.well-known/manifest.json, /.well-known/keybase.txt),因此,不應阻止對其可見內容的訪問。

apacheconf
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_URI} "!(^|/)\.well-known/([^./]+./?)+$" [NC]
    RewriteCond %{SCRIPT_FILENAME} -d [OR]
    RewriteCond %{SCRIPT_FILENAME} -f
    RewriteRule "(^|/)\." - [F]
</IfModule>

阻止訪問包含敏感資訊的檔案

阻止訪問一些文字編輯器可能留下的備份和原始檔,當任何人都可以訪問它們時,這可能會構成安全風險。

更新以下示例中的 <FilesMatch> 正則表示式,以包含任何可能最終出現在您的生產伺服器上並可能洩露有關您網站敏感資訊的檔案。這些檔案可能包括配置檔案或包含專案元資料的檔案等。

apacheconf
<IfModule mod_authz_core.c>
  <FilesMatch "(^#.*#|\.(bak|conf|dist|fla|in[ci]|log|orig|psd|sh|sql|sw[op])|~)$">
    Require all denied
  </FilesMatch>
</IfModule>

HTTP 嚴格傳輸安全 (HSTS)

如果使用者在瀏覽器中輸入 example.com,即使伺服器將他們重定向到網站的安全版本,攻擊者仍然有一個機會視窗(初始 HTTP 連線)來降級或重定向請求。

以下標頭確保瀏覽器僅透過 HTTPS 連線到您的伺服器,無論使用者在瀏覽器位址列中輸入什麼。

請注意,嚴格傳輸安全不可撤銷,您必須確保在 max-age 指令中指定的時間內能夠透過 HTTPS 提供站點。如果您不再擁有有效的 TLS 連線(例如,由於 TLS 證書過期),即使嘗試透過 HTTP 連線,您的訪問者也會看到錯誤訊息。

apacheconf
<IfModule mod_headers.c>
  # Header always set
  Strict-Transport-Security "max-age=16070400; includeSubDomains" "expr=%{HTTPS} == 'on'"
  # (1) Enable your site for HSTS preload inclusion.
  # Header always set
  Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" "expr=%{HTTPS} == 'on'"
</IfModule>

阻止某些瀏覽器對響應進行 MIME 嗅探

  1. 透過將 default-src 指令設定為 'self',預設情況下將所有抓取限制為當前網站的源 - 這作為所有 抓取指令 的回退。

    • 這很方便,因為您無需指定適用於您網站的所有 Fetch 指令,例如:connect-src 'self'; font-src 'self'; script-src 'self'; style-src 'self'
    • 此限制也意味著您必須明確定義允許您的網站從哪些站點載入資源。否則,它將被限制為與發出請求的頁面相同的來源
  2. 禁止在網站上使用 <base> 元素。這是為了防止攻擊者更改從相對 URL 載入資源的位置

    • 如果您想使用 <base> 元素,請改用 base-uri 'self'
  3. 僅允許表單提交來自當前源,使用:form-action 'self'

  4. 透過設定 frame-ancestors 'none',阻止所有網站(包括您自己的網站)將您的網頁嵌入到例如 <iframe><object> 元素中。

    • frame-ancestors 指令有助於避免 點選劫持 攻擊,並且類似於 X-Frame-Options 標頭
    • 支援 CSP 標頭的瀏覽器將忽略 X-Frame-Options,如果同時指定了 frame-ancestors
  5. 透過設定 upgrade-insecure-requests 指令,強制瀏覽器將所有透過 HTTP 提供的資源視為透過 HTTPS 安全載入的資源

    • upgrade-insecure-requests 不確保頂級導航的 HTTPS。如果您想強制網站本身透過 HTTPS 載入,您必須包含 Strict-Transport-Security 標頭
  6. 在所有能夠執行指令碼的響應中包含 Content-Security-Policy 標頭。這包括常用的檔案型別:HTML、XML 和 PDF 文件。儘管 JavaScript 檔案無法在“瀏覽上下文”中執行指令碼,但它們被包含在內以針對 web worker

一些舊版瀏覽器會嘗試猜測資源的 content type,即使伺服器配置中未正確設定。這減少了遭受驅動下載攻擊和跨域資料洩露的風險。

apacheconf
<IfModule mod_headers.c>
    Header always set X-Content-Type-Options "nosniff"
</IfModule>

Referrer 策略

我們為能夠請求(或導航到)其他資源的資源響應中包含 Referrer-Policy 標頭。

這包括常用資源型別:HTML、CSS、XML/SVG、PDF 文件、指令碼和 Worker。

為了完全防止 referrer 洩露,請指定 no-referrer 值。請注意,這可能會對分析工具產生負面影響。

使用以下服務檢查您的 Referrer-Policy

apacheconf
<IfModule mod_headers.c>
  Header always set Referrer-Policy "strict-origin-when-cross-origin" "expr=%{CONTENT_TYPE} =~ m#text\/(css|html|javascript)|application\/pdf|xml#i"
</IfModule>

停用 TRACE HTTP 方法

TRACE 方法雖然看似無害,但在某些情況下可以成功利用以竊取合法使用者的憑據。請參閱 跨站追蹤 (XST) 攻擊OWASP Web 安全測試指南

現代瀏覽器現在阻止透過 JavaScript 發出的 TRACE 請求,但是,已經發現了其他使用瀏覽器傳送 TRACE 請求的方法,例如使用 Java。

如果您可以訪問主伺服器配置檔案,請改用 TraceEnable 指令。

apacheconf
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{REQUEST_METHOD} ^TRACE [NC]
  RewriteRule .* - [R=405,L]
</IfModule>

刪除 X-Powered-By 響應頭

一些框架(如 PHP 和 ASP.NET)會設定一個 X-Powered-By 標頭,其中包含有關它們的資訊(例如,它們的名稱、版本號)

此標頭不提供任何價值,在某些情況下,它提供的資訊可能會暴露漏洞

apacheconf
<IfModule mod_headers.c>
  Header unset X-Powered-By
  Header always unset X-Powered-By
</IfModule>

如果可以,您應該從語言/框架級別停用 X-Powered-By 標頭(例如:對於 PHP,您可以透過在 php.ini 中進行以下設定來完成)。

ini
expose_php = off;

阻止 Apache 在伺服器生成的文件(例如錯誤訊息、目錄列表等)中新增包含伺服器資訊的尾部頁尾行。有關伺服器簽名提供的資訊的更多資訊,請參閱 ServerSignature 指令 文件;有關配置簽名中提供的資訊的更多資訊,請參閱 ServerTokens 指令

apacheconf
ServerSignature Off

修復損壞的 AcceptEncoding

一些代理和安全軟體會篡改或剝離 Accept-Encoding HTTP 標頭。有關更詳細的解釋,請參閱 超越 Gzipping

apacheconf
<IfModule mod_deflate.c>
  <IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
      SetEnvIfNoCase ^(Accept-EncodXng|X-cept-Encoding|X{15}|~{15}|-{15})$ ^((gzip|deflate)\s*,?\s*)+|[X~-]{4,13}$ HAVE_Accept-Encoding
      RequestHeader append Accept-Encoding "gzip,deflate" env=HAVE_Accept-Encoding
    </IfModule>
  </IfModule>
</IfModule>

壓縮媒體型別

使用 AddOutputFilterByType 指令 壓縮所有標記為以下媒體型別之一的輸出。

apacheconf
<IfModule mod_deflate.c>
  <IfModule mod_filter.c>
    AddOutputFilterByType DEFLATE "application/atom+xml" \
      "application/javascript" \
      "application/json" \
      "application/ld+json" \
      "application/manifest+json" \
      "application/rdf+xml" \
      "application/rss+xml" \
      "application/schema+json" \
      "application/geo+json" \
      "application/vnd.ms-fontobject" \
      "application/wasm" \
      "application/x-font-ttf" \
      "application/x-javascript" \
      "application/x-web-app-manifest+json" \
      "application/xhtml+xml" \
      "application/xml" \
      "font/eot" \
      "font/opentype" \
      "font/otf" \
      "font/ttf" \
      "image/bmp" \
      "image/svg+xml" \
      "image/vnd.microsoft.icon" \
      "text/cache-manifest" \
      "text/calendar" \
      "text/css" \
      "text/html" \
      "text/javascript" \
      "text/plain" \
      "text/markdown" \
      "text/vcard" \
      "text/vnd.rim.location.xloc" \
      "text/vtt" \
      "text/x-component" \
      "text/x-cross-domain-policy" \
      "text/xml"
  </IfModule>
</IfModule>

將副檔名對映到媒體型別

使用 AddEncoding 將以下副檔名對映到指定的編碼型別,以便 Apache 可以使用適當的 Content-Encoding 響應頭提供檔案型別(這不會讓 Apache 壓縮它們!)。如果這些檔案型別在沒有適當的 Content-Encoding 響應頭的情況下提供,客戶端應用程式(例如瀏覽器)將不知道它們首先需要解壓縮響應,因此將無法理解內容。

apacheconf
<IfModule mod_deflate.c>
  <IfModule mod_mime.c>
    AddEncoding gzip svgz
  </IfModule>
</IfModule>

快取過期

使用 mod_expires 模組以及 Cache-ControlExpires 標頭,提供具有遙遠過期日期的資源。

apacheconf
<IfModule mod_expires.c>
    ExpiresActive on
    ExpiresDefault                                      "access plus 1 month"

  # CSS
    ExpiresByType text/css                              "access plus 1 year"
  # Data interchange
    ExpiresByType application/atom+xml                  "access plus 1 hour"
    ExpiresByType application/rdf+xml                   "access plus 1 hour"
    ExpiresByType application/rss+xml                   "access plus 1 hour"
    ExpiresByType application/json                      "access plus 0 seconds"
    ExpiresByType application/ld+json                   "access plus 0 seconds"
    ExpiresByType application/schema+json               "access plus 0 seconds"
    ExpiresByType application/geo+json                  "access plus 0 seconds"
    ExpiresByType application/xml                       "access plus 0 seconds"
    ExpiresByType text/calendar                         "access plus 0 seconds"
    ExpiresByType text/xml                              "access plus 0 seconds"
  # Favicon (cannot be renamed!) and cursor images
    ExpiresByType image/vnd.microsoft.icon              "access plus 1 week"
    ExpiresByType image/x-icon                          "access plus 1 week"
  # HTML
    ExpiresByType text/html                             "access plus 0 seconds"
  # JavaScript
    ExpiresByType text/javascript                       "access plus 1 year"
  # Manifest files
    ExpiresByType application/manifest+json             "access plus 1 week"
    ExpiresByType application/x-web-app-manifest+json   "access plus 0 seconds"
    ExpiresByType text/cache-manifest                   "access plus 0 seconds"
  # Markdown
    ExpiresByType text/markdown                         "access plus 0 seconds"
  # Media files
    ExpiresByType audio/ogg                             "access plus 1 month"
    ExpiresByType image/bmp                             "access plus 1 month"
    ExpiresByType image/gif                             "access plus 1 month"
    ExpiresByType image/jpeg                            "access plus 1 month"
    ExpiresByType image/svg+xml                         "access plus 1 month"
    ExpiresByType image/webp                            "access plus 1 month"
    # PNG and animated PNG
    ExpiresByType image/apng                            "access plus 1 month"
    ExpiresByType image/png                             "access plus 1 month"
    # HEIF Images
    ExpiresByType image/heic                            "access plus 1 month"
    ExpiresByType image/heif                            "access plus 1 month"
    # HEIF Image Sequence
    ExpiresByType image/heics                           "access plus 1 month"
    ExpiresByType image/heifs                           "access plus 1 month"
    # AVIF Images
    ExpiresByType image/avif                            "access plus 1 month"
    # AVIF Image Sequence
    ExpiresByType image/avis                            "access plus 1 month"
    ExpiresByType video/mp4                             "access plus 1 month"
    ExpiresByType video/ogg                             "access plus 1 month"
    ExpiresByType video/webm                            "access plus 1 month"
  # WebAssembly
    ExpiresByType application/wasm                      "access plus 1 year"
  # Web fonts
    # Collection
    ExpiresByType font/collection                       "access plus 1 month"
    # Embedded OpenType (EOT)
    ExpiresByType application/vnd.ms-fontobject         "access plus 1 month"
    ExpiresByType font/eot                              "access plus 1 month"
    # OpenType
    ExpiresByType font/opentype                         "access plus 1 month"
    ExpiresByType font/otf                              "access plus 1 month"
    # TrueType
    ExpiresByType application/x-font-ttf                "access plus 1 month"
    ExpiresByType font/ttf                              "access plus 1 month"
    # Web Open Font Format (WOFF) 1.0
    ExpiresByType application/font-woff                 "access plus 1 month"
    ExpiresByType application/x-font-woff               "access plus 1 month"
    ExpiresByType font/woff                             "access plus 1 month"
    # Web Open Font Format (WOFF) 2.0
    ExpiresByType application/font-woff2                "access plus 1 month"
    ExpiresByType font/woff2                            "access plus 1 month"
  # Other
    ExpiresByType text/x-cross-domain-policy            "access plus 1 week"
</IfModule>