HTML也可以实现文件包含

我们知道,很多编程语言都有包含文件的功能,所以代码结构相对比较灵活,
但HTML作为一种文本标记语言,默认是不支持文件包含的!
但是,我们可以通过配置Web服务器让HTML支持文件包含!

SSI(Server Side Include),通常称为"服务器端嵌入"或者叫"服务器端包含",是一种类似ASP基于服务器的网页制作技术。
默认扩展名是 .stm、.shtm 和 .shtml
但我们常用的是是html,如果要在扩展名为 html 的文件使用SSI,就需要对 Apache 进行配置

以 Apache2.2 为例,编辑 httpd.conf,

1、搜索 AddType 和 AddOutputFilter,源码如下:

# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
# AddType text/html .shtml
# AddOutputFilter INCLUDES .shtml

默认是被注释的,需要去掉注释,修改成如下:

# Filters allow you to process content before it is sent to the client.
#
# To parse .shtml files for server-side includes (SSI):
# (You will also need to add "Includes" to the "Options" directive.)
#
AddType text/html .html .shtml
AddOutputFilter INCLUDES .html .shtml

2、搜索 Options Indexes FollowSymLinks 在后面加上 INCLUDES

注意,SSI 确实可以利用 Shell 来执行命令,这个功能是极度危险的,因为它会执行任何包含在 exec 标记中的命令。
如果用户有可能修改你的网页内容,那么你一定要关闭这个功能。
可以在 Options 指令中加上 IncludesNOEXEC 参数,以关闭 exec 功能,同时又保留 SSI。

<Directory /usr/local/www/979137.com>
    Options Includes FollowSymLinks
    AllowOverride None
</Directory>

3、重启Apache,可以使用 include 语法了,如:

<!--#include virtual="/header.html" -->

include 元素能按 file 属性或 virtual 属性判断应该包含的文件。
file 属性是一个相对于当前目录的文件路径,即不能是一个绝对路径(以"/"开头)或包含"../"的路径。
virtual 属性可能更有用,它是一个相对于被提供的文档的URL ,可以以"/"开头,但必须与被提供的文档位于同一服务器上。

Related post

微信公众号:程序员到架构师

最新文章

Return Top