wordpress + apache 配置url rewirte

wordpress + apache 配置url rewirte

原文寫於 2013-08-13 https://github.com/kuitos/kuitos.github.io/issues/2

最近在倒騰幫助中心的過程中接觸到wordpress,爲了方便的調試於是在內網虛擬機上搭建了一個LAMP環境,使用的是網上提供的xampp一鍵安裝包。附上安裝包地址

由於業務的需求,要在各個產品跳轉到幫助中心具體的wordpress之前通過一個頁面去接收請求,然後由該頁面轉發請求,如:

頁面請求 http://help.fenxibao.com/channel/ –> 應用服務器 –> 去部署目錄尋找應用名爲channel的wordpress。

改爲:http://help.fenxibao.com/channel/ –> http://help.fenxibao.com/index.php?app=channel –> index.php做處理 –> 跳轉到指定的wordpress。
自然要到apache下面去做配置,在httpd.conf中加上這些內容(xampp安裝之後apache的配置文件在 /opt/lampp/etc/httpd.conf):

# 這一行配置一定要寫啊,不然下面寫再多的rewrite rule都是白搭啊,說多了都是淚啊。。
RewriteEngine on
<VirtualHost _default_:80>
   RewriteCond %{REQUEST_URI} ^/([a-z0-9_-]+)/$
   RewriteRule ^/([a-z0-9_-]+)/ /index.php?app=$1
</VirtualHost>

這裏對這幾行配置作一下說明:

  • RewriteEngine on : 功能如其名
  • RewriteCond string regexCode : 當string滿足regexCode的正則條件時,執行後面的重寫規則
  • RewriteRule regex1 regex2 : 定義重寫規則,將regex1正則匹配到的部分採用regex2來重寫

具體處理步驟:

  1. 請求url:http://help.fenxibao.com/channel/
  2. 進入RewriteCond : request uri滿足條件^/([a-z0-9_-]+)/$
  3. 進入RewriteRule :重寫請求url中滿足條件^/([a-z0-9_-]+)/ 的部分,將其替換爲/index.php?app=1 1即爲正則匹配到的那部分內容,這裏就是channel
    OK,瀏覽器輸入地址滿心期待奇蹟出現的一刻,結果chrom把wordpress打出來了。。。
    查看中轉頁面代碼:
<?php
        $appName = $_GET['app'];
        if ($appName == "channel"){
                echo $appName;
                header('Location: ../wordpress/index.php');
        } else {
                echo $appName;
        }
?>

在這個中轉界面將請求轉發到 ../wordpress/index.php這個頁面,應該沒問題的,這個請求不符合RewriteCond的條件,應該可以直接訪問應用頁面的。。經過各種嘗試發現在直接訪問/wordpress/index.php時url被重定向成/wordpress/,這樣的話就滿足RewriteCond,於是請求過程變成了:
http://help.fenxibao.com/channel/ –> locahost/index.php?app=channel –> lcoahost/wordpress/index.php –> locahost/wordpress/ –> locahost/index.php?app=wordpress –> echo “wordpress” 。。。
跟蹤lcoahost/wordpress/index.php的源代碼,實在是找不到在哪個地方做了url處理,google wordpress index.php,如獲至寶:

<?php
/*
Plugin Name: Disable Canonical URL Redirection
Description: Disables the "Canonical URL Redirect" features of WordPress 2.3 and above.
Version: 1.0
Author: Mark Jaquith
Author URI: http://markjaquith.com/
*/

    remove_filter('template_redirect', 'redirect_canonical');
?>

將這段代碼做成插件然後在wordpress裏面啓用,瀏覽器鍵入地址,世界頓時清靜。。。
附上地址:http://wordpress.org/support/topic/how-can-i-turn-off-wordpress-indexphp-redirect-to-domain-root
最後只想引用帖子裏的一句回覆,Dude, you rock. That plugin script works like a charm.

後續跟進
在後續操作中發現 RewriteCond %{REQUEST_URI} ^/([a-z0-9_-]+)/$ 這個東西其實是有問題,因爲當我訪問wordpress的具體文章時候,頁面鏈接爲 http://10.200.187.70/wordpress/?p=25之類的鏈接,這個時候頁面竟然又跳轉到中間頁面index.php,然後轉發到了wordpress的首頁。各種嘗試無果的情況下只得用蹩腳的英文去stackoverflow上提問,stack上果然是牛人聚集地啊,給出的回覆:

%{REQUEST_URI} excludes the query string (the part after the ?)`

解決方案:

RewriteCond %{QUERY_STRING} ^$
RewriteRule /([\w-]+)/?$ /test.php?app=$1 [L]

OK,it works!!
讓我再歡呼一句:Dude, you rock. Your codes works like a charm.
附上問題鏈接:這裏

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章