2011-02-23 87 views
0

我需要從一個隨機的網址,以獲取最後一組數字的獲得最後3個數字,網址是這樣的:使用mod_rewrite如何從一個url

/目錄/ directory2/ABCD-123

a,b,c,d等等。可以是任何東西,數字,字母但總是會有間破折號在

我們在這個項目中使用kohana,所以有一些額外的重寫規則在玩,但這是我的到目前爲止...

# Turn on URL rewriting 
RewriteEngine On 

# Installation directory 
RewriteBase /site/ 

# Protect hidden files from being viewed 
<Files .*> 
    Order Deny,Allow 
    Deny From All 
</Files> 

# Protect application and system files from being viewed 
RewriteRule ^(?:application|modules|system)\b - [F,L] 

#My Code Attempts Here 
RewriteCond %{REQUEST_URI} dealership/Listing/     
RewriteRule ([0-9]*)$ index.php/dealership/Listing/$1  

# Allow any files or directories that exist to be displayed directly 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 

# Rewrite all other URLs to index.php/URL 
RewriteRule .* index.php/$0 [PT] 

我嘗試了幾十個配置,設置並研究了Google幾個小時而沒有具體答案。

我已經能夠自己得到123,但從來沒有目錄仍然附加,當我已經嘗試了一些配置,我最終在一個無限循環,並得到一個Apache錯誤。

最終結果將是/ directory/directory2/123

謝謝!

+0

正則表達式是:'^/directory/directory2 /([^ \ - ] +) - ([^ \ - ] +) - ([^ \ - ] +) - )$',a到d將是1美元到4美元,最後3美元是5美元。 – 2011-02-23 18:49:39

+0

感謝Paulo,除了我不需要任何其餘的url只有最後一位數字。 RewriteCond%{REQUEST_URI} /?dir1/dir2 /([a-zA-Z0-9] [ - ]可以讓一些匹配的工作通過觀察模式來消除循環, ])+,只有匹配時才匹配。 RewriteRule([0-9] *)$ ...只是獲取url中的最後一個數字。 – atwsKris 2011-02-23 19:08:00

+0

@Paulo Scardine - 爲什麼不回答? – Xailor 2011-02-23 19:25:42

回答

0

您的規則

RewriteRule ([0-9]*)$ index.php/listing/$1 

是沒有用的,因爲它不會改變REQUEST_URI,所以PHP將無法看到重寫index.php/listing/123,它會看到原來/listing/foo-123。如果添加[L]標誌,它將進入循環,因爲相應的ReqeuestCond將繼續爲真。

通常,您將URL位傳遞給腳本作爲參數,例如

RewriteRule ([0-9]*)$ index.php?listing=$1 [L] 

然而,在這種形式是行不通的,因爲([0-9]*)$任何路徑的結尾匹配空字符串,因此它會導致兩個重寫:

listing/foo-(123) → index.php?listing=123 # this is what you want ... 
index.php()  → index.php?listing=  # ... but it gets rewritten 
index.php()  → index.php?listing=  # no change so this is final 

這是因爲所有的重寫規則是從每一個重寫(無論[L]標誌)後開始計算。

因此,你需要更具體的規則

RewriteRule ^listing/[^/]*-([0-9]*)$ index.php?listing=$1 [L] 

這工作對自己,但它會與你的最終規則互動,使上添加一個條件,以防止它的循環

RewriteCond $0 !^/index.php($|/) # $0 is what the RewriteRule matched 
RewriteRule .* index.php/$0 [L] 
相關問題