2015-10-19 38 views
0

所以我一直在研究一些不按預期工作的重寫規則。這些都是我想重寫一些樣品索取:使用自定義.htaccess重寫規則的意外行爲

/    -> /index.php?page=Home 
/Home   -> /index.php?page=Home 
/Teaching/Foo -> /index.php?page=Teaching&id=Foo 
/Teaching/Bar -> /index.php?page=Teaching&id=Bar 
/Download/ue8 -> /index.php?action=Download&id=ue8 
/Download/24a -> /index.php?action=Download&id=24a 
(default)  -> /index.php?page=Home 
** OR ALTERNATIVELY ** 
(default)  -> /index.php?page=FileNotFound 
(and maybe rewrite the visible URL to /FileNotFound) 

我主要是想隱藏儘可能多的網址,儘可能防止這兩個目錄列表,並直接進入位於特定的文件夾我的文件,只允許訪問通過/Download/FileId可下載的文件,同時通過/Teaching/SomeLecture訪問不同講座的通常頁面。

到目前爲止,我一直用這個片段的/Home/Teaching東西:

RewriteEngine On 
RewriteBase/

# Redirect Trailing Slashes 
RewriteRule ^(.*)/$ /$1 [L,R=301] 

# Handle Front Controller 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^Teaching/([A-Za-z0-9]*)$ index.php?page=Teaching&id=$1 [L] 

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^Home$ index.php?page=Home [L] 

RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s(.*)/index\.php [NC] 
RewriteRule^%1 [R=301,L] 

RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^(.*)$ index.php [L,R=301] 

我不能完全肯定所有這些指令的,我注意到,目前有一些瑕疵吧。

  1. 試圖訪問一個不存在的文件,例如/Files/Bad/Path.pdf,將用戶轉發到/?page=Home,根據(default)的規則,該用戶應重定向到//Home或顯示/index.php?page=FileNotFound的內容,而不必更改URL或重定向到/FileNotFound。我不確定哪種解決方案可能最適合這種情況。
  2. 嘗試訪問一些存在的文件夾會導致無限重定向循環,而不存在的文件夾顯然會重定向到/。在這兩種情況下,我認爲重定向到/FileNotFound是正確的?

請問您能制定出一套適合我的需求的規則嗎?

回答

1

您的.htaccess中有很多冗餘指令。這種替換所有的.htaccess的:

# Turn off mod_spelling 
<IfModule mod_speling.c> 
    CheckSpelling off 
    CheckCaseOnly off 
</IfModule> 

Options -MultiViews 
RewriteEngine On 
RewriteBase/

# block direct access to file and directories in these directories 
RewriteCond %{REQUEST_URI} !\.(?:jpe?g|gif|bmp|png|tiff|css|js)$ [NC] 
RewriteCond %{REQUEST_FILENAME} -d [OR] 
RewriteCond %{REQUEST_FILENAME} -f 
RewriteRule ^(Templates|Files) - [NC,F] 

# remove index.php 
RewriteCond %{THE_REQUEST} /index\.php [NC] 
RewriteRule ^(.*?)index\.php$ /$1 [L,R=301,NC,NE] 

# Redirect Trailing Slashes 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteRule ^(.*)/$ /$1 [L,R=301] 

# Handle Front Controller 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME} !-f 
RewriteRule ^(Download|Teaching)/([\w-]+)/?$ index.php?page=$1&id=$2 [L,QSA,NC] 

RewriteRule ^(Home)?/?$ index.php?page=Home [L,NC,QSA] 

確保測試此之前,清除瀏覽器緩存。

+0

倒數第二行有一個小錯誤,您有'QSA.NC'而不是'QSA,NC'。此外,我遇到了一些有趣的服務器行爲。如果我嘗試訪問文件,它會嘗試更正錯誤輸入的網址,並且在某些情況下,它無法決定並顯示我[this](http://i.imgur.com/cpTq8lX.png)。除了我的規則之外,您是否知道如何完全拒絕直接訪問除index.php之外的文件?除了這個小問題之外,它似乎是我一直在尋找的東西。 –

+0

詳細說明我的評論:當我直接訪問'/ Files/Ana14 /'時,它會轉發到'/ Files/Ana15 /',因爲它是唯一存在類似模式的現有文件夾,然後顯示403錯誤消息。在我的第二種情況下,在300狀態代碼中有多種可能性,但我不想顯示它。在這兩種情況下,我想顯示適當的錯誤頁面。 –

+0

禁用'mod_spelling'確實修復了多個選擇!我想我應該在其他目錄中使用'Deny from all'創建新的'.htaccess'文件來禁止直接訪問這些文件? –