我們已經有很多客户在 VPS 上使用 Nginx,對於剛從 Apache 轉過來的客户最常遇到的一個問題就是怎麼弄 Nginx 下的 rewrite 以及怎麼把 Apache 裏的 .htaccess 轉化成 Nginx,網上關於這方面的資料一大堆,關於 WordPress, discuz, phpcms, ecshop, shopex 等的 rewrite 應有盡有,直接 copy 就可以。還有一個 Nginx 新手常見的問題是拿到這些 rewrite 規則後不知道怎麼改,比如 Nginx 下子目錄的 rewrite 應該改成什麼樣子?/ 下是 WordPress,/bbs 下裝個 discuz,/ 是 discuz,/blog 下裝個 WordPress 或者 / 下是 WordPress,/blog 下再裝個 WordPress 等,這樣的 rewrite 怎麼改呢?弄幾個例子放到我們的 FAQ 裏供參考:

WordPress 安裝在子目錄 /blog 下:

 location /blog/ {
root   /home/www/weixiaoduo.com;
index  index.php index.html index.htm;
if (!-e $request_filename) {
rewrite ^.+/?(/blog/wp-.*) $1 last;
rewrite ^.+/?(/blog/.*.php)$ $1 last;
rewrite ^(.+)$ /blog/index.php?q=$1 last;
}
}

Discuz! 7.2 安裝在子目錄 /bbs 下:

 location /bbs/ {
root   /home/www/weixiaoduo.com;
index  index.php index.html index.htm;
rewrite ^/bbs/archiver/((fid|tid)-[w-]+.html)$ /bbs/archiver/index.php?$1 last;
rewrite ^/bbs/forum-([0-9]+)-([0-9]+).html$ /bbs/forumdisplay.php?fid=$1&page=$2 last;
rewrite ^/bbs/thread-([0-9]+)-([0-9]+)-([0-9]+).html$ /bbs/viewthread.php?tid=$1&extra=page%3D$3&page=$2 last;
rewrite ^/bbs/space-(username|uid)-(.+).html$ /bbs/space.php?$1=$2 last;
rewrite ^/bbs/tag-(.+).html$ /bbs/tag.php?name=$1 last;
}

Discuz! X1.5 安裝在子目錄 /bbs 下:

 location /bbs/ {
root   /home/www/weixiaoduo.com;
index  index.php index.html index.htm;
rewrite ^([^.]*)/topic-(.+).html$ $1/portal.php?mod=topic&topic=$2 last;
rewrite ^([^.]*)/article-([0-9]+)-([0-9]+).html$ $1/portal.php?mod=view&aid=$2&page=$3 last;
rewrite ^([^.]*)/forum-(w+)-([0-9]+).html$ $1/forum.php?mod=forumdisplay&fid=$2&page=$3 last;
rewrite ^([^.]*)/thread-([0-9]+)-([0-9]+).html$ $1/forum.php?mod=viewthread&tid=$2&extra=page%3D$4&page=$3 last;
rewrite ^([^.]*)/group-([0-9]+)-([0-9]+).html$ $1/forum.php?mod=group&fid=$2&page=$3 last;
rewrite ^([^.]*)/space-(username|uid)-(.+).html$ $1/home.php?mod=space&$2=$3 last;
rewrite ^([^.]*)/([a-z]+)-(.+).html$ $1/$2.php?rewrite=$3 last;
if (!-e $request_filename) {
return 404;
}
}

如果對理解 ^([^.]*)/([a-z]+)-(.+).html$ 這樣的正則表達式有困難並對這方面有興趣的話可以看看一些書,最好的一本應該是 O』Reilly 出的 Mastering Regular Expressions(也有中文版:《精通正則表達式》) 。