2014-02-15 28 views
1

有沒有辦法使用.htaccess更改網址,但不要重定向?在htaccess中反向mod_rewrite

我有一個像

<a href="?p=hello_world">Hello World</a> 
在我的腳本(DIR/index.php文件)

聯繫,並希望將URL更改爲url.de/dir/hello_world

我現在的.htaccess文件:

RewriteEngine On 
RewriteCond %{QUERY_STRING} ^p=(.*)$ 
RewriteRule ^(.*)$ /%1? [R,L] 
RewriteRule ^([a-zA-Z0-9-]+)/$ index.php?p=$1 [L] 
RewriteRule ^([a-zA-Z0-9-]+)$ index.php?p=$1 [L] 

,但現在從localhost/dir/?p=hello_world網址變更爲localhost/hello_world沒有/dir。我不知道該目錄的名稱,因爲每個人都應該能夠使用我的項目,而不必在他的服務器上更改.htaccess。

+0

我覺得很難理解應該顯示哪些網址,什麼網址應在服務器上加載。你必須做的,是有一個外部重定向('[R,L]'標誌)到漂亮的網址和一個內部重寫(只有'[L]'標誌)舊的網址。對於匹配'%{THE_REQUEST}'的外部重定向。 [我的這個答案](http://stackoverflow.com/a/20882418/2209007)可能會幫助你。 – Sumurai8

回答

1

您需要使用此代碼:

RewriteEngine On 

# Determine the RewriteBase dynamically (\2 is backreference for string after 1st slash 
RewriteCond %{REQUEST_URI}::$1 ^(.*?/)(.*)::\2$ 
RewriteRule ^(.*)$ - [E=BASE:%1] 

# External redirect from /dir?p=hello_world to /dir/hello_world 
RewriteCond %{THE_REQUEST} \?p=([^\s&]+) [NC] 
RewriteRule^%{ENV:BASE}%1? [R=302,L] 

# Internal rewrite from /dir/hello_world to /dir/index.php?p=hello_world 
RewriteRule ^([a-zA-Z0-9-]+)/?$ %{ENV:BASE}index.php?p=$1 [L,QSA] 
+0

不幸的是,我不知道它應該適用於每個網址的目錄名稱。 – Wikunia

+0

好吧現在嘗試更新代碼。 – anubhava

+0

我複製了它,它改變了嗎?p = hello_world是一個單詞/不幸的是我不明白你的代碼:/ – Wikunia