2017-02-11 60 views
1

首先,我正在嘗試實現: 我正在測試基礎http://example.com/subdir,這是所有子文件夾,index.php和.htaccess所在的位置。htaccess:相對路徑不能正常工作

我有3個組的規則,如在.htaccess(額外的規則刪除):

<IfModule mod_rewrite.c> 
Options +FollowSymlinks 
RewriteEngine on 

# Convert item/edit/xx -> index.php?p=edit&id=xx 
# Convert item/remove/xx -> index.php?p=remove&id=xx 
#RewriteCond %{REQUEST_URI} ^/item [NC] 
#RewriteCond %{QUERY_STRING} ^id=([0-9]+)$ [NC] 
RewriteRule ^item/([a-z]+)/([0-9]+)$ index.php?p=$1&id=$2 [NC,L] 

# Convert category/yyyy -> customer/pagination.php?category=yyyy 

#RewriteCond %{QUERY_STRING} category=([a-zA-Z\s]+)$ 
RewriteRule ^customer/category/([a-zA-Z\s]+)$  customer/pagination.php?category=$1 [NC,L] 


# Convert action/about -> index.php?p=about 
# Convert action/terms -> index.php?p=terms 


#RewriteCond %{QUERY_STRING} p=([a-z]+)$ 
RewriteRule ^action/([a-z]+)$  index.php?p=$1 [NC,L] 

</IfModule> 

我面對的是沒有的RewriteCond工作(給路徑未找到),所以它被註釋掉的第一個問題目前爲止。 RewriteRule在絕對路徑下工作正常(例如RewriteRule^action /([az] +)$ http://example.com/subdir/index.php?p= $ 1 [NC,L]),但是這會導致瀏覽器顯示真實的URL,因此我試圖使它與相對路徑。 我的問題是,在第一次重定向後,左側鏈接的第一部分被添加到路徑中,即http://example.com/subdir在點擊動作/關於鏈接後變爲http://example.com/subdir/action。 定義RewriteBase或將斜線前綴加到URL上只會讓事情變得更糟。 我會感謝一位能夠發現問題根源的鷹眼專家。

+0

我真的不明白你的問題的第二部分。什麼是導致錯誤的示例URL,您希望重定向到什麼路徑,以及它實際重定向到的路徑是什麼? – Anonymous

+0

示例URL是:http://example.com/subdir/action/about。點擊後,它會重定向到正確的關於頁面,但下一個請求的路徑將變爲http://example.com/subdir/action/。因此,當您點擊時,例如,操作/條款鏈接 - 生成的url = http://example.com/subdir/action/action/terms。請注意添加到路徑中的額外「操作」文件夾(我需要重定向到http://example.com/subdir/index.php?p=terms)。所有鏈接都是相對的BTW,例如動作/約。謝謝。 – user2097141

回答

1

第一個問題是%{REQUEST_URI}始終包含完整路徑。所以,你的情況可能被更改爲:

RewriteCond %{REQUEST_URI} ^/subdir/item [NC] 

第二個問題實際上沒有使用的.htaccess來解決。你只需要告訴瀏覽器你想要什麼。所以,你可以使用兩種方法之一。

  1. 使用<base>元素(這將適用於所有相對URI在頁面上):

    <base href="/subdir" /> 
    
  2. 使用相對路徑來在瀏覽器中顯示的網址:

    <a href="terms">Click here</a> 
    

如果你真的想解決問題使用.htaccess,唯一真正的方法是在請求後刪除重複的目錄。

+1

非常感謝,設置有所幫助,但我必須將PHP中的所有標題重定向更改爲絕對路徑,以使所有鏈接都能正常工作。在我得到#RewriteCond%{QUERY_STRING}^id =([0-9] +)$ [NC]後,我會發布完整的代碼。 – user2097141