WordPress 站台適用之 htaccess

由 blue 於 週四, 07/12/2007 - 00:05 發表

如之前提過的統計,目前仍有非常多 WordPress 網站未更新至最新版本,當然這可能是因為更新上的困難、Plugins 的相容問題或是最難處理的懶病爆發。Josiah Cole dot com 也是這些網站之一,因此該站長特別提供了號稱近乎完美的 .htaccess 配置,將下面內容存檔為 .htaccess 並放置於 WordPress 網站根目錄,進而達成下列幾種目的:

1. 保護自身安全 (安全性)
2. 關閉數位簽章 (安全性)
3. 限制上傳大小 (安全性)
4. 保護 wp-config.php (安全性)
5. 限制特定訪客的存取 (安全性,可用性)(此部份需自行添加欲阻擋的對象)
6. 指定發生錯誤時顯示的頁面 (可用性)
7. 關閉目錄瀏覽 (安全性)
8. 將舊有頁面轉向到新的 (選擇性)
9. 關閉圖檔 hotlinking (頻寬)
10. 啟用 PHP 壓縮 (頻寬)
11. 設定合乎規範或標準的網址 (搜尋引擎最佳化,可用性)
12. 避免垃圾迴響攻擊 (安全性,頻寬)
(第 12 點是我加的,原文似乎忘了強調,但 .htaccess 中有,另外其中還有阻擋特定來源參照的部份也沒提及)

每個段落皆有註記,與其完全套用,在此建議不如作參考用途,擇需要的部份使用,並妥善測試,其中 yourdomain 的部份記得更改為你的真實網址或網域。

# protect the htaccess file
<files .htaccess>
order allow,deny
deny from all
</files>

# disable the server signature
ServerSignature Off

# limit file uploads to 10mb
LimitRequestBody 10240000

# protect wpconfig.php
<files wp-config.php>
order allow,deny
deny from all
</files>

#who has access who doesnt
order allow,deny
#deny from 000.000.000.000
allow from all

#custom error docs
ErrorDocument 404 /notfound.php
ErrorDocument 403 /forbidden.php
ErrorDocument 500 /error.php

# disable directory browsing
Options All -Indexes

#redirect old to new
Redirect 301 /old.php <a href="http://www.yourdomain.com/new.php" title="http://www.yourdomain.com/new.php">http://www.yourdomain.com/new.php</a>

#block referring domains
RewriteEngine on
RewriteCond %{HTTP_REFERER} digg\.com [NC]
RewriteRule .* - [F]

#disable hotlinking of images with forbidden or custom image option
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain.com/.*$ [NC]
#RewriteRule \.(gif|jpg)$ - [F]
#RewriteRule \.(gif|jpg)$ <a href="http://www.yourdomain.com/stealingisbad.gif" title="http://www.yourdomain.com/stealingisbad.gif">http://www.yourdomain.com/stealingisbad.gif</a> [R,L]

# php compression - use with caution
<ifmodule mod_php4.c>
php_value zlib.output_compression 16386
</ifmodule>

# set the canonical url
RewriteEngine On
RewriteCond %{HTTP_HOST} ^yourdomain\.com$ [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [R=301,L]

# protect from spam comments
RewriteEngine On
RewriteCond %{REQUEST_METHOD} POST
RewriteCond %{REQUEST_URI} .wp-comments-post\.php*
RewriteCond %{HTTP_REFERER} !.*yourdomain.com.* [OR]
RewriteCond %{HTTP_USER_AGENT} ^$
RewriteRule (.*) ^http://%{REMOTE_ADDR}/$ [R=301,L]

備註: 如果你已經用了 WordPress 的 Customize Permalink Structure 功能,記得要將原本 .htaccess 內容合併過來,若直接用新的取代的話,Permalink Structure 將會失效。如果不方便在主機上操作,想知道目前 .htaccess 檔案內容,可透過 WordPress 功能表 Manage>Files>.htaccess 查看。