如何轉換類似使用Apache的mod_rewrite解析SEO友好的URL的
me.com/profile/24443/quincy-jones
到
me.com/profile.php?id=24443
或類似
me.com/store/24111/robert-adams
到
me.com/store.php?id=24111
用mod_rewrite?
我可以使用mod_rewrite進行反向轉換,還是我必須通過PHP解析它?
如何轉換類似使用Apache的mod_rewrite解析SEO友好的URL的
me.com/profile/24443/quincy-jones
到
me.com/profile.php?id=24443
或類似
me.com/store/24111/robert-adams
到
me.com/store.php?id=24111
用mod_rewrite?
我可以使用mod_rewrite進行反向轉換,還是我必須通過PHP解析它?
這應該兩個工作:
RewriteEngine on
RewriteRule ^([^/]+)/([^/]+).*$ $1.php?id=$2 [L]
說明:
^ - beginning of the string
([^/]) - first group that doesn't contain/
will match both 'profile' and 'store'
will also be referenced by $1 later
/ - first slash separator
([^/]) - second group, id in your case
will be referenced by $2
.* - any ending of the request uri
$ - end of request string
您也可以使之更精確所以只有兩個要求被重寫,只有數字被接受爲ID:
RewriteRule ^((profile|store))/(\d+).*$ $1.php?id=$2 [L]
確保您已啓用mod_rewrite apache模塊,然後:
RewriteEngine on
RewriteRule ^/profile/([^/]*)/([^/]*)$ /profile.php?id=$1 [L]
RewriteRule ^/store/([^/]*)/([^/]*)$ /store.php?id=$1 [L]
您可能想要處理PHP中的逆向條件,特別是尾部名稱部分(因爲它不在原始URL中)。如果你想在mod_rewrite中沒有名字來處理它,請確保你不會以雙重重寫(取決於你的規則的順序)。此外,您可以使用[L](上一個)開關將規則作爲最後一個使用(如果匹配,後續規則將被跳過)。
此外,可以制定更通用的重寫規則,但您需要仔細考慮可能受到影響的其他URL。
+1,對於說明 – Starx 2012-11-02 05:00:28