不少朋友總是詢問 WordPress 如何新增偽靜態規則,今天珞凡就總結一下 IIS/Apache/Nginx 三種環境下的偽靜態規則,希望對大家有所幫助。檢測主機是否支援偽靜態的方法:在 WP 後臺 > 設定 > 固定連結,設定自定義結構,然後訪問任何一篇文章,如果出現 404 錯誤,說明你的主機當前不支援 WordPress 偽靜態。
IIS 偽靜態規則
IIS 環境是 Windows 主機常用的伺服器環境,新建一個 txt 檔案,將下面的程式碼新增到檔案中:
[ISAPI_Rewrite]
# Defend your computer from some worm attacks
#RewriteRule .*(?:global.asa|default.ida|root.exe|..).* . [F,I,O]
# 3600 = 1 hourCacheClockRate 3600
RepeatLimit 32# Protect httpd.ini and httpd.parse.errors files
# from accessing through HTTP
# Rules to ensure that normal content gets throughRewriteRule /tag/(.*) /index.php?tag=$1
RewriteRule /software-files/(.*) /software-files/$1 [L]
RewriteRule /images/(.*) /images/$1 [L]
RewriteRule /sitemap.xml /sitemap.xml [L]
RewriteRule /favicon.ico /favicon.ico [L]
# For file-based wordpress content (i.e. theme), admin, etc.
RewriteRule /wp-(.*) /wp-$1 [L]
# For normal wordpress content, via index.php
RewriteRule ^/$ /index.php [L]
RewriteRule /(.*) /index.php/$1 [L]
然後另存為 httpd.ini 檔案,上傳到 WordPress 站點的根目錄即可。
Apache 偽靜態規則
Apache 是 Linux 主機下常見的環境,現在一般的 Linux 虛擬主機都採用這種環境。新建一個 htaccess.txt 檔案,新增下面的程式碼:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
然後上傳到 WordPress 站點的根目錄,重新命名為 .htaccess 即可。
Nginx 偽靜態規則
Nginx 環境一般是 Linux 主機 VPS 或伺服器使用者用的比較多,這些使用者一般都會自己配置 Nginx,或者有專門的人幫你配置,開啟 nginx.conf 或者某個站點的配置環境,比如 wpdaxue.com.conf(不同人配置的不一樣),在 server { } 大括號裡面新增下面的程式碼:
location / {
if (-f $request_filename/index.html){
rewrite (.*) $1/index.html break;
}
if (-f $request_filename/index.php){
rewrite (.*) $1/index.php;
}
if (!-f $request_filename){
rewrite (.*) /index.php;
}
}
儲存,重啟 Nginx 即可。
題外話:珞凡不推薦在 windows 的 IIS 伺服器下安裝 WordPress,因為 IIS 環境執行 php 程式的效率,相對同等配置下 Linux 的 Apache 和 Nginx 環境,要低的多。實踐證明,Linux 主機的 PHP 環境更加有利於高效執行 WordPress 等 PHP 程式,比如對偽靜態的支援、對中文連結的支援,對其他 WordPress 所需函式的支援更加完美,執行更加流暢。如果你使用 windows 主機,你會發現,執行 Wordpress 感覺比較慢,而且通常不能完美支援偽靜態,而且網址中有中文的話,就會出現 404 錯誤,有時候還沒辦法使用某些外掛……