2017-02-04 48 views
1

讓我們假設我有這個文件夾結構的Apache服務器上的靜態網站:的.htaccess檢查文件是否在多個子文件夾存在並改寫

http://www.example.com 
|  
+-- /news/ 
| | 
| +-- page1.html 
| +-- page2.html 
| +-- ... 
| 
+-- /otherstuff/ 

的/新聞/文件夾內的頁面的網址是:

http://www.example.com/news/page1.html 
http://www.example.com/news/page2.html 

現在,在/新聞/文件夾中的文件的數量在不斷增長,我想中創建新的子文件夾在這些新的目錄/新聞/和分割文件,但我也想隱藏子文件夾名稱在網址中。

新的文件夾結構將是:

http://www.example.com 
|  
+-- /news/ 
| | 
| +-- /subfolder1/ 
| | | 
| | +-- page1.html 
| | 
| +-- /subfolder2/ 
| | | 
| | +-- page2.html 
| +-- ... 
| 
+-- /otherstuff/ 

頁面的URL都保持不變

http://www.example.com/news/page1.html 
http://www.example.com/news/page2.html 

http://www.example.com/news/subfolder1/page1.html 
http://www.example.com/news/subfolder2/page2.html 

有沒有辦法使用.htaccess中的重寫規則實現此結果?

我讀過這樣一個問題: How to use mod_Rewrite to check multiple folders for a static file

,但接受的答案並不爲我工作。

在此先感謝您的任何建議。

回答

1

您可以使用下面的規則/news/.htaccess:

RewriteEngine on 

RewriteCond %{DOCUMENT_ROOT}/subfolder/$1.html -f 
RewriteRule ^(.*?)\.html$ /news/subfolder/$1 [L] 

這將改寫/news/file.html/news/subfolder/file.html如果file.html存在於/news/subfolder/

如果你的htaccess是根,你可以試試下面的

RewriteEngine on 

RewriteCond %{DOCUMENT_ROOT}/news/subfolder/$1.html -f 
RewriteRule ^news/(.*?)\.html$ /news/subfolder/$1.html [L] 

如果上面的例子中失敗了,你可以在根或新聞/的.htaccess試試這個:

RewriteEngine on 

RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^(?:news/)?(.*?)\.html$ /news/subfolder/$1.html [L] 
+0

您好,感謝您的幫助。我試過你的代碼,但仍然沒有運氣:即使/news/subfolder/file.html中的文件存在,url /news/file.html也會提供404。我開始認爲服務器變量有問題,因爲如果我轉到/news/subfolder/news1.html代碼%{DOCUMENT_ROOT} /news/subfolder/$1.html變爲C:/ xampp/htdocs /新聞/子文件夾/新聞/子文件夾/ file.html – Francesco2810

+0

是的,這是一些服務器上的問題。我會爲你發佈一個工作解決方案。 – starkeen

+0

@ francesco2810請參閱編輯 – starkeen

相關問題