Apache 配置 SSI 支持 include 调用公用的页头页脚

这篇文章是为了实现前端人员编写项目众多静态文件时,能像 php 等开发语言一样使用 include 将页面的 header/footer/sidebar 等公共模块作为公用、独立、单一的文件引入到页面上,这样就能单独修改一次对应的独立文件,实现全站更新,方便快捷。

为了实现以上所述,我们需要开启 SSI 配置使 shtml 支持 include 公用的页头页脚;

关于什么是 shtml/SSI 请自行 Google;

Apache 默认是不开启支持 SSI 的,需要我们更改 httpd.conf 来进行配置。
我这里以 Windows 平台的 Apache 为例,打开 conf 目录下的 httpd.conf 文件,搜索 “AddType text/html .shtml”,找到:

#AddType text/html .shtml
#AddOutputFilter INCLUDES .shtml

把这两行前面的 # 去掉,就能在后缀名为 shtml 的页面中使用 SSI 的 include 语法,如果想在 html/htm 页面中也能使用 SSI 的 include 功能,我们需要添加文件后缀名使 SSI 支持,修改如下:

AddType text/html .shtml .html .htm
AddOutputFilter INCLUDES .shtml .html .htm

我们看到这两行的上面会有一句注释提示:# (You will also need to add "Includes" to the "Options" directive.)
意思就是说除了修改这2行,还需要在你的服务器项目配目录配置的 Options 项中添加 Includes,才能正常使用 SSI 的 include 功能。

注意:在多数配置中,多个Options指令会互相覆盖,所以,可能必须对需要 SSI 的特定目录使用 Options,以确保对应配置起作用

PS:
我在 Apache 的 httpd-vhosts.conf 文件添加了下面的虚拟主机:

<VirtualHost *:80>
ServerName www.debug.org
DocumentRoot "D:/Project"
DirectoryIndex index.html index.php index.shtml
ErrorLog "logs/eims-error.log"
CustomLog "logs/eims-access.log" combined
<Directory "D:/Project">
Options Indexes FollowSymLinks
AllowOverride all
Order Allow,Deny
Allow from all
</Directory>
</VirtualHost>

该主机域名:www.debug.org,对应虚拟目录是:D:/Project,那我们就应该在该虚拟主机中定位到 Options Indexes FollowSymLinks 并在该项最后添加关键字:Includes,即修改后为:

<VirtualHost *:80>
ServerName www.debug.org
DocumentRoot "D:/Project"
DirectoryIndex index.html index.php index.shtml
ErrorLog "logs/eims-error.log"
CustomLog "logs/eims-access.log" combined
<Directory "D:/Project">
Options Indexes FollowSymLinks Includes
AllowOverride all
Order Allow,Deny
Allow from all
</Directory>
</VirtualHost>

保存 httpd.conf,重起 Apache 即可,到此我们就完成了对 Apache SSI 的设置。

完成 SSI 配置,使 Apache 能解析 SSI 的 shtml 页面的 include 语法,下面就来说下页面中怎么使用 include 命令。

PS: 我们要在根目录的 index.shtml 引用根目录下的 include 目录下的 header.html 页面,我们可以这样写:

引用相对当前虚拟目录的header文件:
<!--#include virtual="includes/header.html" --><!--#include virtual="/includes/header.html" -->

路径要写正确,路径不正确会报错:[an error occurred while processing this directive]

扩展阅读:
SSI include 命令 路径问题,可查看下面文章:
http://blog.csdn.net/xtra6714/article/details/7097634

用shtml来include网页文件:
http://www.chinaz.com/design/2007/0419/7118.shtml

SSI配置参考文章:
http://jingyan.baidu.com/article/4ae03de323cc903eff9e6bea.html

不用apache,Windows7中IIS简单安装与配置SSI:
http://ons.me/147.html

SSI配置及命令介绍:
http://man.chinaunix.net/newsoft/ApacheManual/howto/ssi.html#page-header

原文:http://www.phpvar.com/archives/3278.html

发表评论
* 昵称
* Email
* 网址
* 评论