2014-02-17 31 views
1

我的目標是如http://mydomain.com/somenamehttp://mydomain.com/somename.html重定向任何URL除了http://mydomain.com/name1http://mydomain.com/name2對於這兩個,我希望他們重定向到http://mydomain.com/main.php?g1=name1(或名2等)。如果後面兩個在URL中有兩個或三個以上的目錄(即http://mydomain.com/name1/val2/val3),我希望將它們作爲單獨的GET值添加,如http://mydomain.com/main.php?g1=name1&g2=val2&g3=val3。我希望瀏覽器繼續顯示目錄路徑,而不是像http://mydomain.com/somename.html有條件重定向目錄結構的URL到HTML文件

以下是我不成功的嘗試。我怎樣才能做到這一點?謝謝

<IfModule mod_rewrite.c> 
RewriteEngine on 
RewriteBase/

## If the request is for a valid directory, file, or link, don't do anything 
RewriteCond %{REQUEST_FILENAME} -d [OR] 
RewriteCond %{REQUEST_FILENAME} -f [OR] 
RewriteCond %{REQUEST_FILENAME} -l 
RewriteRule^- [L] 

RewriteCond %{REQUEST_URI} !^/name1 [OR] RewriteCond %{REQUEST_URI} !^/name2 
RewriteRule ^(.*)$ $1.html [L] 

RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ ?p=$1&c=$2&v=$3 [L,QSA] 
RewriteRule ^([^/]+)/([^/]+)/?$ p=$1&c=$2 [L,QSA] 
RewriteRule ^([^/]+)/?$ ?p=$1 [L,QSA] 

</IfModule> 

回答

1

你在大多數地方正確的想法,但你需要改變你的規則的順序不太具體的東西之前,以匹配更具體的東西。通常,我允許在下面的規則中通過/?在尾部/。如果您不允許匹配尾部/,請從頭到尾將其刪除。

RewriteEngine on 
RewriteBase/

# This should be fine as you have it.... 
## If the request is for a valid directory, file, or link, don't do anything 
RewriteCond %{REQUEST_FILENAME} -d [OR] 
RewriteCond %{REQUEST_FILENAME} -f [OR] 
RewriteCond %{REQUEST_FILENAME} -l 
RewriteRule^- [L] 

# Reverse your rule order here. 
# First match name1|name2 with an optional trailing/
# but nothing else following... 
RewriteRule ^(name1|name2)/?$ main.php?g1=$1 [L,QSA] 
# Two additional dirs 
RewriteRule ^(name1|name2)/([^/]+)/([^/]+)/?$ main.php?g1=$1&g2=$2&g3=$3 [L,QSA] 
# Three additional dirs 
RewriteRule ^(name1|name2)/([^/]+)/([^/]+)/([^/]+)/?$ main.php?g1=$1&g2=$2&g3=$3&g4=$4 [L,QSA] 

# Last, do the generic rule to rewrite to .html 
# using [^.]+ to match anything not including a . 
# You could be more specific with something like [a-z]+ if that 
# corresponds to your expected input 
RewriteRule ^([^.]+)$ $1.html [L,QSA] 

如果你想檢查URI是沒有條件name1, name2,使用[AND]這是隱式:

RewriteCond %{REQUEST_URI} !/name1 
RewriteCond %{REQUEST_URI} !/name2 
RewriteRule ^([^.]+)$ $1.html [L,QSA] 
+0

我認爲你的意思'$ 4'底有。 –

+0

@PanamaJack是的,謝謝。 –

+0

Michael,你太棒了!我一直在爲此瘋狂。只是好奇,但可能會創建一個條件,它不是名稱1或名稱2,然後執行HTML重寫? – user1032531