萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

.htaccess 重定向與 URL 重寫實戰範例大全

.htaccess 是 Apache 虛擬主機目錄下的分散式配置文件,可實現 URL 重寫、重定向、訪問控制、錯誤頁面自定義等功能,無需修改主配置文件即可生效。本文彙總常用實戰範例,助您快速掌握核心語法。

基礎配置

# 註解行以 # 開頭
# 指定默認首頁查找順序
DirectoryIndex index.htm index.php

# 自定義 404 錯誤頁
ErrorDocument 404 /error/404.html

重定向指令

簡單重定向 (mod_alias)

# 302 臨時重定向:訪問 /abc 顯示 /def 內容,地址欄仍顯示 /abc
Redirect /abc /def

# 301 永久重定向:地址欄同步變為 /def
Redirect 301 /abc /def

# 整站目錄重定向
Redirect /olddirectory /newdirectory

URL 重寫 (mod_rewrite)

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 訪問控制

# 封禁單一 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 狀態碼

進階技巧

限制 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>

強制 HTTPS

RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

調試建議

  1. 啟用重寫日誌:RewriteLog "/var/log/rewrite.log" RewriteLogLevel 3(僅主配置文件有效)
  2. 測試規則前先備份原 .htaccess
  3. 使用 curl -I 檢查響應頭確認跳轉狀態碼
  4. 避免在高併發生產環境濫用複雜正則,影響性能

總結

.htaccess 功能強大但需謹慎使用。重定向首選 Redirect 指令簡潔高效;複雜邏輯才用 mod_rewrite。安全配置務必配合主配置文件 AllowOverride 權限設置,防止配置失效或洩露敏感信息。

copyright © 萬盛學電腦網 all rights reserved