2012-11-18 85 views
2

我知道如何添加目錄斜槓實際的目錄,但我需要添加結尾的斜槓上虛擬目錄 - 這樣,當用戶訪問example.com/website/blog/項其中/博客& /條目都是虛擬目錄),URL地址會發生物理變化到:example.com/website/blog/entries/強制目錄中的虛擬目錄斜線與htaccess的

這裏是我當前的工作htaccess的代碼工作轉換假/虛擬目錄爲參數,我的PHP腳本:

RewriteRule ^/?([a-zA-Z_\-/.]+)$ index.php?file=$1 [L,QSA] 

重寫規則使得example.com/website/blog/entries/樣子example.com/website/index.php?file=blog/entries/到PHP只,而不是用戶。

這裏有一些重寫規則我試圖讓工作與無濟於事:

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule .*[^/]$ %{REQUEST_URI}$1/ [L,R=301] 

# ----------------------------------------------- 

RewriteCond %{REQUEST_URI} ^(.+)/$ 
RewriteRule ^.+/$ %1 [R=301,L] 

我相信這個問題是因爲我的那個虛擬目錄轉換成參數當前正則表達式查找的目錄名開始以「/」,所以當在根文件夾沒有安裝該網站(「/」),或者如果沒有尾隨斜線,它重定向到一些完全錯誤的。我無法在我的htaccess文件中的任何位置編寫文件夾路徑,因爲路徑會不斷變化。舉例來說,我不能用這樣的:

RewriteRule ^(.*)$ http://localhost:8888/project/$1/ [L,R=301] 

有沒有辦法來強制實結尾的斜槓,和虛擬目錄,之前轉換的虛擬目錄到PHP參數?

回答

1

像下面這樣的東西應該做你需要什麼:

RewriteEngine On 

# Put here the URL where .htaccess is located 
RewriteBase /project/ 

# Redirect virtual URLs w/o trailing slash to URL with it 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*[^/])$ $1/ [R=301,QSA,L] 

# pass virtual URLs into index.php as file argument 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^/?([a-zA-Z_\-/.]+)$ index.php?file=$1 [L,QSA] 

,因爲它們出現在配置,從而重定向將數據傳遞到index.php中

以前做過的規則的順序處理

這裏是版本W/O使用RewriteBase與URL的硬編碼部分:

RewriteEngine On 

# Redirect virtual URLs w/o trailing slash to URL with it 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_URI} ^(.*[^/])$ 
RewriteRule .* %1/ [R=301,QSA,L] 

# pass virtual URLs into index.php as file argument 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_URI} ^/?([a-zA-Z_\-/.]+)$ 
RewriteRule .* index.php?file=%1 [L,QSA] 
+0

這是近乎完美的,並回答我的問題,但我必須避免使用靜態主任你的名字。你知道通過請求獲取.htaccess文件所在目錄的方法嗎?以類似%{} REQUEST_DIR,即可以抓住目錄的名稱沒有我身體寫作「/項目/」?謝謝你的回答! –

+0

@deraad看到更新的答案。應該像你期望的那樣工作,即使沒有硬編碼的'/ project /' –

+0

我也沒有按照你的建議使用硬編碼的「/ project /」名稱,但它不起作用,因爲它重定向到了錯誤的地方。相反,我寫了一個PHP腳本來重新創建子目錄的名稱,它安裝在網站中的htaccess文件。 –