.htaccess 是一個簡單的文字文件,可讓您控制 Web 伺服器如何處理請求。雖然它最初是為管理目錄存取而設計的,但現在它可以用於許多其他用途。
本指南並未深入探討 .htaccess 而是一個包含有用程式碼片段集合的實用介紹。儘管 .htaccess 雖然功能強大,但這並不意味著你應該將它用於一切。了解何時以及如何應用它可以提高您網站的安全性、效能和功能。
什麼是 .htaccess?
这 .htaccess 文件是“超文本存取”的縮寫,是主要用於 Apache 伺服器.它允許使用者控制存取權限、密碼保護目錄、設定重定向、自訂錯誤頁面以及阻止特定的 IP 位址。
與 .htpasswd 檔案配對,它可以為多個使用者提供細粒度的目錄存取控制。許多託管服務提供者支持 .htaccess,但它並不通用——一些 Web 伺服器(如 Nginx)使用不同的方法。
在哪裡可以找到你的 .htaccess 文件?
缺省情況下, .htaccess 檔案隱藏在 cPanel 的檔案總管和其他託管控制面板中。您可以透過在檔案總管設定中啟用「顯示隱藏檔案」選項來顯示它。
如果您找不到該文件,請不要驚慌——它可能還不存在。大多數情況下,它應該位於您的網站的根目錄中,通常名為 public_html 或 www。如果您在同一個託管帳戶下管理多個網站,則每個網站可能都有自己的 .htaccess 文件位於其各自的資料夾中。
大多數以句點 (.) 開頭的系統檔案都是隱藏的。如果你的 .htaccess 文件不可見,請檢查您的託管設定或在文字編輯器中手動建立一個。
.htaccess 備忘單和程式碼範例
而 .htaccess 可以做很多事情,了解正確的命令是關鍵。為了方便起見,我們整理了一份最常用的 .htaccess 規則。無論您需要阻止惡意機器人,強制 HTTPS自訂錯誤頁面或改進 SEO,您會在下面找到可立即使用的程式碼片段。
只需複製、貼上並調整它們即可滿足您的需求。讓我們開始吧!
提醒:使用任何規則之前,請仔細檢查並驗證。對於可能出現的任何問題,我們概不負責-使用風險由您自行承擔。此外,大多數規則都要求 RewriteEngine On 指令 .htaccess 文件才能正常運作。
重寫和重定向規則
用一個服務所有請求 PHP 文件 .htaccess
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^?]*)$ /index.php [NC,L,QSA]
WordPress .htaccess 對於永久連結 .htaccess
(這是本節中唯一包含 RewriteEngine 規則的規則。)
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
強制使用 www .htaccess
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301,NC]
以通用方式強制使用 www .htaccess
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
強制使用非 www .htaccess
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ https://example.com/$1 [L,R=301]
以通用方式強制使用非 www .htaccess
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|off
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)?(.+)$
RewriteRule ^ %1%3%{REQUEST_URI} [R=301,L]
實力 HTTPS - .htaccess
使用此重定向非 HTTPS 請求 HTTPS 要求。例如,如果您造訪 https://example.com/,它將重定向到 https://example.com。
RewriteEngine on
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
實力 HTTPS 在代理後面 .htaccess
如果您的伺服器前面有一個執行 TLS 終止的代理,則很有用。
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
強制使用尾部斜杠 .htaccess
使用關注 .htaccess 規則將任何不以尾部斜線結尾的請求重定向到相同的 url(但帶有尾部斜線)。即從 https://example.com/your-page 重定向到 https://example.com/your-page/
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]
刪除尾部斜槓 .htaccess
使用它來刪除任何尾隨斜線(它將 301 重定向到非尾隨斜線 URL)
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [R=301,L]
重定向單一頁面 .htaccess
將單一 URL 重新導向到新位置
Redirect 301 /oldpage.html https://www.yoursite.com/newpage.html
Redirect 301 /oldpage2.html https://www.yoursite.com/folder/
使用以下方式為單一目錄設定別名 .htaccess
RewriteEngine On
RewriteRule ^source-directory/(.*) target-directory/$1
腳本的別名路徑 .htaccess
RewriteEngine On
RewriteRule ^$ index.fcgi/ [QSA,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.fcgi/$1 [QSA,L]
這個例子有一個 index.fcgi 某個目錄中的文件,並且該目錄中任何無法解析文件名/目錄的請求都會被傳送到 index.fcgi 腳本。如果你願意的話 baz.foo/some/cool/path 由...處理 baz.foo/index.fcgi (也支援以下請求 baz.foo)同時保持 baz.foo/css/style.css 等等。
重定向整個網站 .htaccess
使用以下內容 .htaccess 將整個網站重新導向到新位置/網域的規則
Redirect 301 / https://newsite.com/
這樣,連結就完整了。那是 www.oldsite.com/some/crazy/link.html 會變成 www.newsite.com/some/crazy/link.html。當您只是將網站「移動」到新網域時,這非常有用。
使用以下方式為「乾淨」 URL 命名 .htaccess
此程式碼片段可讓您使用“乾淨的 URL” - 那些沒有 PHP 擴展,例如 example.com/users 而不是 example.com/users.php.
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^.]+)$ $1.php [NC,L]
安全規則
拒絕所有訪問 .htaccess
如果您想阻止 apache 提供任何文件,請使用以下命令。
這將阻止您訪問您的網站。如果您想拒絕所有訪問但仍能自己查看,請閱讀下一條規則:
Deny from all
拒絕除您之外的所有存取(僅允許某些 IP) .htaccess
使用此功能僅允許某些 IP 位址存取您的網站。
# Require all denied
# Require ip xxx.xxx.xxx.xxx
xxx.xxx.xxx.xxx 是你的IP。例如,如果您將最後三位數字替換為 0/12,這將指定同一網路內的一系列 IP,從而省去了單獨列出所有允許的 IP 的麻煩。
請參閱下一條規則以了解此規則的“反面”!
使用以下方式封鎖 IP 位址 .htaccess
這將允許存取除列出的 IP 之外的所有 IP。您可以使用此功能允許除垃圾郵件發送者的 IP 位址之外的所有存取。
將 xxx.xxx.xxx.xxx 和 xxx.xxx.xxx.xxy 替換為您要封鎖的 IP 位址。
Apache 2.4
# Require all granted
# Require not ip xxx.xxx.xxx.xxx
# Require not ip xxx.xxx.xxx.xxy
僅允許從 LAN 進行存取 .htaccess
order deny,allow
deny from all
allow from 192.168.0.0/24
拒絕存取某些用戶代理(機器人) .htaccess
使用此 .htaccess 阻止/禁止某些用戶代理的規則
RewriteCond %{HTTP_USER_AGENT} ^User\ Agent\ 1 [OR]
RewriteCond %{HTTP_USER_AGENT} ^Another\ Bot\ You\ Want\ To\ Block [OR]
RewriteCond %{HTTP_USER_AGENT} ^Another\ UA
RewriteRule ^.* - [F,L]
拒絕存取隱藏檔案和目錄 .htaccess
隱藏檔案和目錄(名稱以點開頭的檔案和目錄) .) 應該在大多數(如果不是全部)時間內得到保障。例如: .htaccess、.htpasswd、.git、.hg。
RewriteCond %{SCRIPT_FILENAME} -d [OR]
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule "(^|/)\." - [F]
或者,你也可以提出 Not Found 錯誤,攻擊者毫無頭緒:
RedirectMatch 404 /\..*$
拒絕存取某些文件 .htaccess
使用它來阻止或拒絕存取某些文件
<files your-file-name.txt>
order allow,deny
deny from all
</files>
拒絕存取備份和來源文件 .htaccess
這些文件可能是由一些文字/html 編輯器(如 Vi/Vim)留下的,當任何人都可以存取它們時,會帶來巨大的安全隱患。
<FilesMatch "(\.(bak|config|dist|fla|inc|ini|log|psd|sh|sql|swp)|~)$">
## Apache 2.2
Order allow,deny
Deny from all
Satisfy All
## Apache 2.4
# Require all denied
</FilesMatch>
禁用目錄瀏覽 .htaccess
Options All -Indexes
啟用目錄列表 .htaccess
Options All +Indexes
禁用某些文件類型的列表 .htaccess
使用此選項可以排除某些檔案類型 Apache 目錄清單。您可以使用它來阻止 .pdf 檔案或視訊檔案的顯示。
IndexIgnore *.zip *.mp4 *.pdf
禁用圖像熱鏈接 .htaccess
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]
重定向熱鏈接器並顯示不同的圖像 .htaccess
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https://(www\.)?your-website.com/.*$ [NC]
RewriteRule \.(gif|jpg|png)$ https://www.your-website.com/do-not-hotlink-our-content.jpg [R,L]
拒絕來自某些推薦人的訪問 .htaccess
使用此規則可以阻止對包含來自特定網域的引薦來源的請求的存取。
RewriteCond %{HTTP_REFERER} block-this-referer\.com [NC,OR]
RewriteCond %{HTTP_REFERER} and-block-traffic-that-this-site-sends\.com [NC]
RewriteRule .* - [F]
使用密碼保護目錄 .htaccess
首先,您需要在系統中的某個位置建立一個.htpasswd 檔案。在命令列中執行以下命令:
htpasswd -c /home/hidden/directory/here/.htpasswd the_username
然後您就可以使用它進行身份驗證。在你的 .htaccess 檔案您需要類似以下程式碼的內容,但請確保 AuthUserFile 是您剛剛建立的 .htpasswd 的檔案路徑。您應該將 .htpasswd 保存在無法透過網路存取的目錄中。所以不要將其放在您的 /public_html/ 或 /www/ 目錄中。
AuthType Basic
AuthName "Password Protected Dir Title"
AuthUserFile /home/hidden/directory/here/.htpasswd
Require valid-user
使用密碼保護一個或多個文件 .htaccess
AuthName "Password Protected Directory Title"
AuthType Basic
AuthUserFile /home/hidden/directory/here/.htpasswd
<Files "/a-private-file.txt">
Require valid-user
</Files>
<FilesMatch ^((one|two|three)-rings?\.o)$>
Require valid-user
</FilesMatch>
績效規則
使用以下方法壓縮文字文件 .htaccess
<IfModule mod_deflate.c>
# Force compression for mangled headers.
# https://developer.yahoo.com/blogs/ydn/posts/2010/12/pushing-beyond-gzipping
<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>
# Compress all output labeled with one of the following MIME-types
# (for Apache versions below 2.3.7, you don't need to enable `mod_filter`
# and can remove the `<IfModule mod_filter.c>` and `</IfModule>` lines
# as `AddOutputFilterByType` is still in the core directives).
<IfModule mod_filter.c>
AddOutputFilterByType DEFLATE application/atom+xml \
application/javascript \
application/json \
application/rss+xml \
application/vnd.ms-fontobject \
application/x-font-ttf \
application/x-web-app-manifest+json \
application/xhtml+xml \
application/xml \
font/opentype \
image/svg+xml \
image/x-icon \
text/css \
text/html \
text/plain \
text/x-component \
text/xml
</IfModule>
</IfModule>
設定過期標頭 .htaccess
過期標頭 告訴瀏覽器是否應該從伺服器請求特定檔案還是僅從快取中取得。建議將靜態內容的過期標頭設定為將來的某個時間。
如果您不使用基於檔案名稱的快取破壞來控製版本控制,請考慮將 CSS 和 JS 等資源的快取時間降低到 1 週左右。
<IfModule mod_expires.c>
ExpiresActive on
ExpiresDefault "access plus 1 month"
# CSS
ExpiresByType text/css "access plus 1 year"
# Data interchange
ExpiresByType application/json "access plus 0 seconds"
ExpiresByType application/xml "access plus 0 seconds"
ExpiresByType text/xml "access plus 0 seconds"
# Favicon (cannot be renamed!)
ExpiresByType image/x-icon "access plus 1 week"
# HTML components (HTCs)
ExpiresByType text/x-component "access plus 1 month"
# HTML
ExpiresByType text/html "access plus 0 seconds"
# JavaScript
ExpiresByType application/javascript "access plus 1 year"
# Manifest files
ExpiresByType application/x-web-app-manifest+json "access plus 0 seconds"
ExpiresByType text/cache-manifest "access plus 0 seconds"
# Media
ExpiresByType audio/ogg "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "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"
# Web feeds
ExpiresByType application/atom+xml "access plus 1 hour"
ExpiresByType application/rss+xml "access plus 1 hour"
# Web fonts
ExpiresByType application/font-woff2 "access plus 1 month"
ExpiresByType application/font-woff "access plus 1 month"
ExpiresByType application/vnd.ms-fontobject "access plus 1 month"
ExpiresByType application/x-font-ttf "access plus 1 month"
ExpiresByType font/opentype "access plus 1 month"
ExpiresByType image/svg+xml "access plus 1 month"
</IfModule>
使用以下方式關閉電子標籤 .htaccess
透過刪除 ETag 標頭,您可以停用快取和瀏覽器驗證檔案的能力,因此它們被迫依賴您的 Cache-Control 和 Expires 標頭。
<IfModule mod_headers.c>
Header unset ETag
</IfModule>
FileETag None
限制上傳檔案大小 .htaccess
以位元組為單位輸入檔案大小。 。下面的程式碼將其限制為 1mb。
LimitRequestBody 1048576
其他規則
mod_rewrite 的伺服器變數 .htaccess
%{API_VERSION}
%{DOCUMENT_ROOT}
%{HTTP_ACCEPT}
%{HTTP_COOKIE}
%{HTTP_FORWARDED}
%{HTTP_HOST}
%{HTTP_PROXY_CONNECTION}
%{HTTP_REFERER}
%{HTTP_USER_AGENT}
%{HTTPS}
%{IS_SUBREQ}
%{REQUEST_FILENAME}
%{REQUEST_URI}
%{SERVER_ADDR}
%{SERVER_ADMIN}
%{SERVER_NAME}
%{SERVER_PORT}
%{SERVER_PROTOCOL}
%{SERVER_SOFTWARE}
%{THE_REQUEST}
套裝 PHP 變數 .htaccess
php_value <key> <val>
例如:
php_value upload_max_filesize 50M
php_value max_execution_time 240
自訂錯誤頁面 .htaccess
ErrorDocument 500 "Houston, we have a problem."
ErrorDocument 401 https://error.yourdomain.com/mordor.html
ErrorDocument 404 /errors/halflife3.html
更新時將使用者重新導向到維護頁面 .htaccess
這會將使用者重新導向到維護頁面,但允許存取您的 IP 位址。將 555.555.555.555 變更為您的 IP,將 YourMaintenancePageFilenameOrFullUrlUrl.html 變更為您的錯誤頁面(或不同網域上的整個 URL)。
ErrorDocument 403 YourMaintenancePageFilenameOrFullUrlUrl.html
Order deny,allow
Deny from all
Allow from 555.555.555.555
強制下載 .htaccess
有時您想要強制瀏覽器下載某些內容而不是顯示它。以下程式碼片段將會有所幫助。
<Files *.md>
ForceType application/octet-stream
Header set Content-Disposition attachment
</Files>
停用顯示伺服器資訊(伺服器簽章) .htaccess
雖然許多人認為這毫無意義(特別是在安全性方面),但如果您想阻止伺服器洩露伺服器資訊(伺服器作業系統等),請使用以下命令:
ServerSignature Off
防止下載 .htaccess
有時您想要強制瀏覽器顯示某些內容而不是下載它。以下程式碼片段將會有所幫助。
<FilesMatch "\.(tex|log|aux)$">
Header set Content-Type text/plain
</FilesMatch>
允許跨域字體 .htaccess
CDN由於 CROS,提供的 webfonts 可能無法在 Firefox 或 IE 中運作。以下來自 alrra 的片段應該可以實現這一點。
<IfModule mod_headers.c>
<FilesMatch "\.(eot|otf|ttc|ttf|woff|woff2)$">
Header set Access-Control-Allow-Origin "*"
</FilesMatch>
</IfModule>
自動 UTF-8 編碼 .htaccess
具有 Apache 自動以 UTF-8 編碼您的內容,請使用以下程式碼。如果需要,您也可以將 utf-8 替換為其他字元集:
# Use UTF-8 encoding for anything served text/plain or text/html
AddDefaultCharset utf-8
# Force UTF-8 for a number of file formats
AddCharset utf-8 .atom .css .js .json .rss .vtt .xml
使用以下方式設定伺服器時區(UTC 或其他時區) .htaccess
SetEnv TZ UTC
查看時區清單。要將其設定為洛杉磯時區:
SetEnv TZ America/Los_Angeles
切換到另一個 PHP 版本 .htaccess
如果你在共享主機上,那麼可能會有多個版本的 PHP 安裝,有時您希望為您的網站安裝特定的版本。例如,要求 PHP >= 5.4。以下程式碼片段應該切換 PHP 版本適合您。
AddHandler application/x-httpd-php55 .php
或者,您可以使用 AddType
AddType application/x-httpd-php55 .php
停用 Internet Explorer 相容性視圖
IE 中的相容性視圖可能會影響某些網站的顯示方式。以下程式碼片段應強制 IE 使用 Edge Rendering Engine 並停用相容性視圖。
<IfModule mod_headers.c>
BrowserMatch MSIE is-msie
Header set X-UA-Compatible IE=edge env=is-msie
</IfModule>
執行 PHP 使用不同的檔案副檔名 .htaccess
以下程式碼將使用 php 運行以 .ext 結尾的檔案:
AddType application/x-httpd-php .ext
如果存在,則自動提供 WebP 影像
如果支援 WebP 映像,並且在與要提供的 jpg/png 映像相同的位置找到具有 .webp 副檔名且名稱相同的映像,則提供 WebP 映像。
RewriteEngine On
RewriteCond %{HTTP_ACCEPT} image/webp
RewriteCond %{DOCUMENT_ROOT}/$1.webp -f
RewriteRule (.+)\.(jpe?g|png)$ $1.webp [T=image/webp,E=accept:1]
設定主機往往不太容易。因此我們推出 HostScore 安裝協助服務 替您一次到位完成正確的主機配置。
我們能協助您完成 SSL 安裝、DNS 與名稱伺服器設定、WordPress 安裝或移轉,以及安全優化。一次性收費,並提供 100% 退款保證。
了解我們的服務結束語
这 .htaccess 文件是一個強大的工具,但明智地使用它很重要。雖然添加額外的規則來快速解決問題可能很誘人,但請記住 .htaccess 不是主設定檔。
每次伺服器遇到 .htaccess 文件,它必須讀取並執行它,覆蓋主配置設定。此過程會消耗資源並可能降低您的網站速度,尤其是過度使用時。只要有可能,就直接在伺服器層級套用設定(例如,在 Apache的主配置檔案)以獲得更好的性能。
通過使用 .htaccess 高效地搭配 優化的託管計劃 – 您可以增強網站的安全性、效能和可擴充性
樂樂 Q & A
我應該使用 .htaccess?
從全球使用意義上來說 .htaccess 文件可以提供很多便利。然而,這可能會增加伺服器資源的成本。盡可能依賴主伺服器配置,而不是 .htaccess 文件。
我怎麼知道我的 .htaccess 工作中?
確保你的 .htaccess 檔案是否正常運作的方法是存取放置它的目錄的 URL。如果它不工作,您可能會遇到 500 內部伺服器錯誤。
我可以有多個嗎 .htaccess 文件?
.htaccess 從技術上講,文件可以放置在您想要配置的每個目錄中。如果您執行多個網站,則每個主目錄都可以有自己的檔案 - 以及其下的每個子目錄中的一個檔案。
htaccess 中的重寫規則是什麼?
重寫 Apache 允許您重寫 URL 請求的模組。它只是接收傳入的請求並將其定向到您指定的請求以代替它。