2015-10-19 83 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'文件来禁止直接访问这些文件? –