2014-01-15 31 views
0

我想配置.htaccess文件來重新路由所有的URL到最近的指數子目錄,這樣的:使用。 htaccess的重寫的URL中的子目錄只

http://example.com/admin/blah/test/whatever應該留在地址欄,而是指向:

如果url是一個實際的文件,它應該總是去那個文件。所以http://example.com/admin/blah/file.csshttp://example.com/admin/blah/item.inc都應該仍然工作,否則它應該重定向到該文件夾​​中的index.php或最近的父文件夾,如上所示。

我也想這隻影響一個子文件夾,如果這是可能的話。在上面的例子中,我假設.htaccess文件將進入/ admin /文件夾。

更新: 下面是當前工作:

# No Directory Listings or trailing slashes 
Options -Multiviews -Indexes +FollowSymLinks 

<IfModule mod_rewrite.c> 

RewriteEngine On 
DirectorySlash Off 

# See if the current request is a directory containing an index file 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME}/index.php -f 
RewriteRule ^(.*)/?$ $1/index.php [L,QSA] 


# if index.php doesn't exist in current dir then 
# forward to the parent directory of current REQUEST_URI 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{DOCUMENT_ROOT}/$1$2/index.php !-f 
RewriteRule ^(.*?/)?([^/]+)/?$ $1 [L,QSA] 

</IfModule> 

這主要工作。如果輸入http://example.com/admin?p=2,則按預期解決問題,但如果使用網址http://example.com/admin/?p=2,則也可以解決此問題,而不會明確刪除尾部斜槓。

+0

如果您需要子文件夾特定的規則,請將.htaccess文件放在子文件夾中。 –

回答

0

下面是最終的工作。

在我的.htaccess文件我有:

# No Directory Listings 
Options -Multiviews -Indexes +FollowSymLinks 

<IfModule mod_rewrite.c> 

RewriteEngine On 
DirectorySlash Off 

# see if the current directory contains an index file 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{REQUEST_FILENAME}/index.php -f 
RewriteRule ^(.*)/?$ $1/index.php [L,QSA] 


# if index.php doesn't exist in current dir then 
# forward to the parent directory of current REQUEST_URI 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{DOCUMENT_ROOT}/$1$2/index.php !-f 
RewriteRule ^(.*?/)?([^/]+)/?$ $1 [L,QSA] 

</IfModule> 

鏈接現有目錄查找該目錄中的index.php文件。現有文件的鏈接顯示該文件。其他一切都重定向到我的index.php。從那裏,我可以正常閱讀$ _GET的任何查詢,並且我可以讀取並解析完整的URL以查看要顯示的頁面。這也適用於一個子目錄,如果我不希望它適用於整個網站。

1

這是相當棘手的規則。在您的DOCUMENT_ROOT/.htaccess文件中試試這個:

RewriteEngine On 
RewriteBase/

# if index.php doesn't exist in current dir then 
# forward to the parent directory of current REQUEST_URI 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteCond %{DOCUMENT_ROOT}/$1$2/index.php !-f 
RewriteRule ^(.*?/)?([^/]+)/?$ $1 [L] 
+0

這似乎運作良好。我注意到的一件事是在我的本地測試服務器上,我在根目錄中的子文件夾中有多個站點,所以我必須將RewriteBase硬編碼爲/ sitefolder /,這在測試環境中不是問題。然而,有趣的是:它的效果很好,示例url和localhost/sitefolder/subfolder/index.php轉到了正確的文件,但是localhost/sitefolder/subfolder/index.php /去了localhost/ 可能只是一個測試服務器怪癖。我會做一些更多的測試並在一分鐘內回覆。 – Michelle

+0

非常感謝您的幫助。它可以工作,但只有一個小問題: 我添加了[L,QSA]來保存任何查詢字符串,這很好用,但是,有什麼方法可以刪除結尾的斜槓嗎?目前,網址是這樣的:http://example.com/admin/?p=3,我想這個http://example.com/admin?p=3如果我嘗試使用它,它會添加斜槓回退。 – Michelle

+0

此規則不會添加尾部斜線。另外如果'/ admin /'是一個目錄,那麼'mod_dir'模塊會添加結尾斜槓。 – anubhava