.htaccess 是 Apache 虛擬主機目錄下的分散式配置文件,可實現 URL 重寫、重定向、訪問控制、錯誤頁面自定義等功能,無需修改主配置文件即可生效。本文彙總常用實戰範例,助您快速掌握核心語法。
# 註解行以 # 開頭
# 指定默認首頁查找順序
DirectoryIndex index.htm index.php
# 自定義 404 錯誤頁
ErrorDocument 404 /error/404.html
# 302 臨時重定向:訪問 /abc 顯示 /def 內容,地址欄仍顯示 /abc
Redirect /abc /def
# 301 永久重定向:地址欄同步變為 /def
Redirect 301 /abc /def
# 整站目錄重定向
Redirect /olddirectory /newdirectory
RewriteEngine On
RewriteBase /
# 內部重寫:訪問 old.html 實際執行 index.php,地址欄不變
RewriteRule ^old.html$ index.php
# 外部 301 重定向:地址欄跳轉至 /index.php
# RewriteRule ^old.html$ /index.php [R=301,L]
# 強制 www 域名(含 301 跳轉)
RewriteCond %{HTTP_HOST} ^111cn.net [NC]
RewriteRule ^(.*)$ https://www.111cn.net/$1 [L,R=301]
<Files "index.php">
AuthName "Restricted Area"
AuthType Basic
AuthUserFile /absolute/path/to/.htpasswd
Require valid-user
</Files>
注意: AuthUserFile 必須使用絕對路徑,否則報 500 錯誤。.htpasswd 格式為 username:encrypted_password,建議存放於 Web 根目錄外。
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https://www.111cn.net/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^https://111cn.net/.*$ [NC]
RewriteRule \.(jpg|jpeg|gif|png|bmp|js|css|swf)$ https://www.google.com [R,NC]
# 封禁單一 IP
Deny from 127.0.0.10
# 封禁整個 C 段
Deny from 210.10.56.
# 僅允許特定 IP
Allow from 127.0.0.10
Order Deny,Allow
Deny from all
Options -Indexes
ErrorDocument 404 /err/404.php
ErrorDocument 503 /err/503.php
# 支援 400、403、500 等所有 HTTP 狀態碼
<Limit GET POST>
Require valid-user
</Limit>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
</IfModule>
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteLog "/var/log/rewrite.log" RewriteLogLevel 3(僅主配置文件有效).htaccesscurl -I 檢查響應頭確認跳轉狀態碼.htaccess 功能強大但需謹慎使用。重定向首選 Redirect 指令簡潔高效;複雜邏輯才用 mod_rewrite。安全配置務必配合主配置文件 AllowOverride 權限設置,防止配置失效或洩露敏感信息。