Apache中强制指定文件解析类型的方法

admin 2021年9月14日14:29:01评论58 views字数 1659阅读5分31秒阅读模式

在IIS中,可以很方便的规定文件的解析类型。比如一个网站里有上传模块,为了安全起见,如果没有特殊需求,最好将上传文件所在目录的解析类型强制全部指定为binary-octstream,用户在访问任何文件链接时均会直接下载到本机,而不会在服务器端解析后再返回。这样可以杜绝asp、php木马,提高安全性。
而在Apache中如何配置呢?一般情况下会首先想到AddType、Header set content-type或者.htaccess中采用Rewrite Engine。搜索这个问题也通常会得到这三种解释。但问题在于,如果你加载了mime_module,它有一个配置文件,TypesConfig conf/mime.types,在你的apache目录下打开这个文件,会看到很多预定义好的解析类型,Http Server文件解析会优先交给它来做。这样的话,前两种方法在mime_module模块存在下事实上是无效的。而.htaccess虽然可行,但如果我们想把所有的文件全部指定为octstream,每个文件类型都要写规则麻烦且不可行。那我们该如何方便快捷的去完成这个任务?

答案是:ForceType。
以下摘自Apache Http Server文档

ForceType Directive

Description: Forces all matching files to be served with the specified MIME content-type
Syntax: ForceType MIME-type|None
Context: directory, .htaccess
Override: FileInfo
Status: Core
Module: core
Compatibility: Moved to the core in Apache 2.0

When placed into an .htaccess file or a <Directory>, or <Location> or <Files> section, this directive forces all matching files to be served with the content type identification given by MIME-type. For example, if you had a directory full of GIF files, but did not want to label them all with .gif, you might want to use:

ForceType image/gif

Note that unlike DefaultType, this directive overrides all mime-type associations, including filename extensions, that might identify the media type.
You can override any ForceType setting by using the value of None:

# force all files to be image/gif:
<Location /images>
ForceType image/gif
</Location>

# but normal mime-type associations here:
<Location /images/mixed>
ForceType None
</Location>

使用mime_module中的ForceType即可。
本文开头的问题就有了明确的解答:ForceType application/octet-stream即可。设置完成后再访问这个目录下的文件时就会直接下载,而不会再去解析。
这个技巧可能很简单,但我当时为了解决它搜了很多文章,却都没有正确答案。在此也感谢Sakura对我的提醒和指点,指出了mime.types是问题的一个根源。
有的时候有问题了,直接去看文档,或许要比漫无目的的搜索要方便很多:)

 

FROM :https://blog.flanker017.me/ | Author:Flanker

  • 左青龙
  • 微信扫一扫
  • weinxin
  • 右白虎
  • 微信扫一扫
  • weinxin
admin
  • 本文由 发表于 2021年9月14日14:29:01
  • 转载请保留本文链接(CN-SEC中文网:感谢原作者辛苦付出):
                   Apache中强制指定文件解析类型的方法https://cn-sec.com/archives/542659.html

发表评论

匿名网友 填写信息