How to include one HTML file inside another

How to include one HTML file inside another 12Feb, 2010

Including an HTML file inside another HTML file can be achieved using Apache’s SSI (Server Side Include). In this article, we’ll stick to the topic only and for further details on usage and scope of SSI you may refer to this article.

Configuring your server to permit SSI

To permit SSI on your server, you must have mod_include installed and enabled. Generally, this should be installed in Apache by default. Additionally, you must have the following directive either in your httpd.conf file, or in a .htaccess file:

Options +Includes

Not just any file is parsed for SSI directives. You have to tell Apache which files should be parsed. There are the following two ways to do this:

  • You can tell Apache to parse any file with a particular file extension, such as .shtml, with the following directives:

AddType text/html .shtml
AddHandler server-parsed .shtml

One disadvantage of this approach is that if you wanted to add SSI directives to an existing page, you would have to change the name of that page, and all links to that page, in order to give it a .shtml extension, so that those directives would be executed.

Although you don’t need the files to have .shtml – they can be .html as well. The thing to keep in mind is that, by doing this, you’re requiring that Apache read through every single file that it sends out to clients, even if they don’t contain any SSI directives. This can slow things down quite a bit, and is not a good idea.

  • The other method is to use the XBitHack directive:

 

XBitHack on

XBitHack tells Apache to parse files for SSI directives if they have the execute bit set. So, to add SSI directives to an existing page, rather than having to change the file name, you would just need to make the file executable using chmod.

chmod +x pagename.html

Basic SSI directives

Having done the above, you can include the HTML file using the following SSI directives:

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

It is formatted like an HTML comment, so if you don’t have SSI correctly enabled, the browser will ignore it, but it will still be visible in the HTML source. If you have SSI correctly configured, the directive will be replaced with its results.

Posted by: Aman Brar / In: HTML and Tagged , ,
Cam