如何防止脚本在目录中运行?

时间:2012-06-25 12:45:51

标签: security .htaccess

我的web根文件夹中有我的图像存储文件目录,我想知道如何保护该文件夹。我阻止人们将脚本上传到该文件夹​​,我检查文件扩展名,如果它不是图像,那么它将不会保存到该文件夹​​。

但伪装扩展很容易完成,如果有人设法将脚本上传到我的文件目录并从浏览器访问它会发生什么呢?

所以我需要一种方法来阻止脚本在该文件夹中运行,并且只允许运行图像。

我知道htaccess可以做到这一点,但我不知道如何设置它。我的.htaccess文件是这样的:

AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi
Options -ExecCGI
ForceType application/octet-stream
<FilesMatch "(?i)\.(gif|jpe?g|png)$">
  ForceType none
</FilesMatch>
Options All -Indexes

但它无法正常工作,我在该文件夹中保存了一个php文件,然后尝试从浏览器访问它,我仍然可以访问它。你知道怎么做这个吗?或者如果你有更安全的方法,请告诉我。

谢谢

1 个答案:

答案 0 :(得分:1)

我认为它没有用,因为你只有添加了一个额外的处理程序,你还没有删除其他处理程序。

最简单的方法是将另一个.htaccess文件放在要保护的文件夹中(而不是弄乱匹配指令),其中包含:

# Fix PHP, you should do matching commands for JSP and ASP, & html
RemoveType application/x-httpd-php php
# .... add the other remove-handler statements here .... #

# Optionally make these equivalent to text files.
# UPDATE: Taken this out as you dont want people to see PHP files at all
#AddType text/html php

# To disable cgi and server side includes & indexes
# You need to check the setup of Apache, some of the file types
# listed should already be handled as CGI (.pl, .py, .sh)
Options -ExecCGI -Includes -Indexes

# Completely block access to PHP files
<FilesMatch "\.(php|phps|html|htm|jsp|asp)$">
    Order allow,deny
    Deny from all
</Files>
# Add in any additional types to block

这包括PHP和CGI,你应该为JSP和ASP做匹配的命令

更新:添加了完全阻止访问PHP文件的代码 - 抱歉,最初认为您根本不想让它们执行。另请注意,我已经注释掉将PHP文件转换为文本文件的行。