HOW TO USE INCLUDES AND SSI FILES-- A TUTORIAL WITH X-BIT HACK

 

 ud 03/24/2006 06:58 AM -0600 Bookmark this page now!


Monday
Google


PHP Include files

Let's look at some things:
     Why Use Include Files?
     View Code for hardcoder.com Include Files
     How to Use Include Files in PHP
     How to Use Include Files in ASP

Why Use Include Files?

I like modular code. I like making changes to just a few files and having those changes propagated throughout the entire web site without having to edit every single file. Include files help make this happen.

For example, every page at hardcoder.com has a separate header and footer file included. The header file includes the start of the HTML page and opens the table I put all my content into. The footer file closes the table and contains the footer links if any. This way I don't have to edit every single page whenever a link changes, or when I want to change the look of the site - I can simply edit the header.php file in each of the directories and make my changes there. There is a different header.php file in each directory because the left hand navigation changes depending on what section you're in. The footer files remain pretty constant throughout the site, though I can customize the footers as well.

I also include a file called format.php in every header.php file. The format.php file includes definitions of my most commonly used variables - for example, I define all my fonts, my paragraph tags, base href, and other variales that will make writing my content files just that much easier. Using variables in my code lets me change them easily. For hardcoder.com, my default font face is "Arial, Helvetica, sans-serif". If I decide that I don't like that font - I can simply change the "" variable in my format file and it will effect this change across the entire web site. One format.php file is used for the entire site.

I also keep my functions in separate include file(s) so that pages that don't need that code included can be kept free from the extra kb.

How to Use Include Files in PHP

The PHP configuration file lets you set up an auto_prepend and auto_append files (header & footer files) which automatically get included on every file. The only downfall to this is that sometimes you may not want to include a header and footer file. If you have the auto_prepend and auto_append feature turned on, and you do not have the appropriate files in the directory you're trying to view a file in, it will not serve the file out. For example, say you want to view index.php in www.website.com/temp and the php3.ini file is configured to auto prepend/append header.php/footer.php and these two files are missing from the /temp directory, you will get a fatal error when it fails to open the files it needs to include.

If you use the auto_prepend and auto_append feature, you do not need to add any additional code to your pages. The PHP engine will automatically add those files. You can also choose to take advantage of the include_path. You can set this to your default include directory (say /includes) and when you add the include tag to your php pages, it will look first in the directory that particular page resides in to see if there is a file by the name of the include file and if not, will include the file by that name in the default include path you've configured.

For example, if you have a default file that you want to include in many of your files, say a company information file with name, address, phone number, you can call this "co_info.php" and put it in your default includes directory. But in the Store directory of your company's website, you want to post additional or different company info so you created a different "co_info.php" file and put it in your Store directory. On all your php pages, you'll include the tag, <? include("co_info.php") ?>. When a visitor comes to that page, PHP will check to see if there is a "co_info.php" page in its current directory and if there isn't one, it will include the "co_info.php" from the default include directory.

The PHP code to include files is:

<? include("filename.php") ?>

How to Use Include Files in ASP

There are two ways to include files in ASP. With the "include file" or "include virtual" options. "Include virtual" tells ASP where the include file is relative to the web root directory, "include file" tells ASP where the file is relative to the current directory. Use either of the following tags to include files in ASP:

<!-- #include virtual="/includes/header.asp" -->
(tells ASP where the file is located relative to the root web directory)

<!-- #include file="../includes/header.asp" -->
(tells ASP where the file is relative to its current directory)

NOTE: Do not put any spaces between the open bracket (<), exclamation mark (!), or the 2 dashes (--). If you put ASP code in the include files, make sure that the code is enlosed in opening & closing ASP brackets ( <% %> ). The include file tags should be placed outside of the opening and closing ASP tags on the calling file.

 
Misspelled words on this page 

 


 

Server Side Includes

The Server allows you to create documents which include other documents and various dynamically generated information, such as the current date, the file's last modification date, and the size or last modification of other files. Note: The "exec" command is not available, due to security considerations.

Special File Extension Necessary

Files utilizing includes must end in ".shtml". If they do not, the includes will be ignored.

The "include" format

All include directives are formatted as SGML comments within your document. This is in case the document should ever be transferred without being parsed. Each directive has the following format: <!--#command tag1="value1" tag2="value2" -->

Each command takes different arguments, most only accept one tag at a time. Here is a breakdown of the commands and their associated tags:

include
config
other commands

include

Inserts the text of a specified document into the body of the current document. Is commonly used for including headers or footers in web pages.

<!--#include virtual="/dir/file.ext"-->
<!--#include file="subdir/file.ext"-->

 
Notes:
  • Do not leave any spaces between the equal ("=") sign and the file it specifies. Doing so will cause an error message to be displayed.
  • Any included file is subject to the usual access authorization controls.
  • If you use a domain name you must use the virtual command. file only works with WebCom URLs.
  • virtual gives a virtual path to a document on the server. A normal file or another parsed document may be accessed using this tag. Please note that the path of this file name should be the URL of the file, with the domain name removed, and the userid added. For instance, if the URL of a file is "http://www.your-domain.com/products/footer.txt" and your userid is "userid" then the path to use with this include directive would be: "/userid/products/footer.txt"

    Example: <!--#include virtual="/virtual_sample.txt"-->

    This is a sample text file . It was included in this file by the include virtual tag:
    <!--#include virtual="/webcom/virtual_sample.txt"--> . file gives a pathname relative to the current directory. ../ cannot be used in this pathname, nor can absolute paths be used. (If you need to refer to a file in a higher directory, you might consider using virtual described above.) As above, you can send other parsed documents.

    <P> This is a <A HREF="http://www.webcom.com/webcom/virtual_sample.txt">sample text file</A>. It was included in this file by the include virtual tag:<BR> <CODE>&lt;!--#include virtual="/webcom/virtual_sample.txt"&gt;</CODE>. </P>

     

     

    Example: <!--#include file="sample.txt"-->

    This is a sample text file . It was included in this file by the include file tag: <!--#include file="sample.txt"-->.

    Misspelled words on this page 

     

    SSI: The Include Command

    Use these to jump around or read it all...
    [ Can You Run SSI? ]
    [ Types of SSI ]
    [ The Include Command ]
    [ The File Argument ]
    [ The Virtual Argument ]
    [ The Included File ]

    SSI: Server Side Include

    This is a topic that has been requested over and over again by readers. Server Side Includes (SSIs) are PERL language-based commands that allow information to be gathered from the server. It works a lot like ASP .

    Actually, I should say ASP works a lot like this, as this was around first. The concept is to use the server to gather and post information. That way you're not dealing with browser version problems. The thing that is being included is included before it gets to the browser so versions never come into play.

    Most UNIX servers are set up to run SSI. Those of you on WindowsNT-based servers might have to go with ASP to get a lot of these effects, but check first before you decide you can't run these commands. You might be able to.

    Can You Run SSI?

    The easiest way to check is to post a file that tried to grab something from the server. Copy what is below and paste it into a document.

    <HTML>
    <TITLE>Test File</TITLE>

    <!--#config timefmt="%A" --> <!--#echo var="DATE_LOCAL" -->

    </HTML>

    Save it as an HTML file and upload it to your server. Then use your browser to look at it. You should see the current day name (Monday, Tuesday, Wednesday... you get the idea). If you see the day name, you're good to go.

    If not, try saving the file with the extension .shtml . See the "s" I stuck in there? That "s" acts as a parsing command alerting the server that there's something on the page it has to play with.

    Many servers are configured to parse all pages thus you probably won't need to set the page to .shtml, but you might.

    If both attempts fail, you can try contacting your server people to see if they'll configure the server for you, but they probably won't or they would have already.

    If it works, read on. You're in for some good commands ahead.

    Types of SSI

    There are an absolute slew of Server Side Include commands. In order to keep this tutorial from being just a mind-numbing run of text, I have broken it into three sections:
    • Commands that include another file (this tutorial)
    • Commands that display dates and time from the server ( Click Here )
    • Commands that display file information ( Click Here )

    The Include Command

    When you mention SSI, this is the event most people think of. Here's the concept:

    You have 500 files on your Web site. At the top of each of the files is a greeting that you'd like to change daily. You could either go into every page, every day, and change the greeting or you could have a text file that each of your 500 files include. Then you would change just that one text page and all the other pages would update. That's the concept of the include command.

    Every page on the HTML Goodies Web site uses include commands, but you'd never know it by looking at the source code. When you View Source on one of the Goodies pages, there is text and coding galore before you actually get to the meat of the tutorial. I don't write any of that. I use an include to get the job done. Two lines of code, and all that text just magically pops in there.

    Here's how you do it. ====>

     

     

    The File Argument

    Under the heading of the include command there are two arguments. These arguments work much the same as an attribute under an HTML tag. An example would be the SIZE attribute under the FONT tag.

    The format of any include command line looks like this:

    <!--#command argument="value" -->

    The command (in this case "include") is followed by the argument (in this case "file") and then what "file" represents.

    Sharp-eyed HTML folk will notice that the format looks a lot like an HTML comment. Basically, it is. This command line will not appear on the page. What will appear is the file it represents.

    Please Note This:

    The format for these SSI command lines is not at all forgiving. You must do the coding correctly or it simply will not work. If it doesn't work, there's no error message to help you. You're left high and dry and wondering what the heck is wrong. Try very hard to get it right the first time.

    Follow these rules:

    • Commands and arguments are in lowercase letters
    • The double quotes around the value are required
    • There is no space until after the command
    • That hash mark (#) is required
    • There is a space after the second double quote, before the second double hyphen (at the end)

    That's not being too picky is it?

    That said, let's look at the format of the File Argument:

    <!--#include file="included.html" -->

    The format above will create an SSI that will include the text found in the file "included.html".

    Why Use "file="?

    You use "file=" when the file that will be included is held within the same directory as the file that is calling for it. You can also use the file argument when the file is within a subdirectory of the directory containing the file that is calling for it. This is the one I use every time I create an SSI.

    The Virtual Argument

    You would use the virtual argument if the file you are calling for is located in a position requiring an address starting at the server root. That's an academic way of saying the file isn't in the same directory as the page that's calling for it.

    Maybe you'll set up a directory unto itself that contains all of your include files. This is a popular method of doing things. If so, then you'll use the virtual argument to attach the SSI command to the files. Just make a point of giving the command the path from the server root (the domain name). Like so:

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

    That forward slash before the first directory is representative of the domain name (server root). By using that leading slash, the server will add the domain name to the front of the address for you.

    Rule of Thumb

    Use "file=" when the included file is within the same directory as the page that wants it. Use "virtual=" when it isn't.

    The Included File

    Let me talk about the file that will be included before wrapping this up. I like to use HTML files to include, but you don't have to. You can use a simple .txt text file. I like to use .html files because if they are hit upon by accident, they display. It may not be a good reason, but it's why I do it.

    Please do not think that because the file that is being included is set to the extension .html that it has to be a fully formed HTML document. It does not. If all you want to include is one line of text, then that's all that should be on that file. If you include a title and a body command and all the other items required of a traditional HTML document, all of that will be included in the SSI and you do not want that.

    So... in the file you are setting up to be included, put only what you want to be included in that file, nothing more. Yes, it'll look sparse, but remember that it should not be standing on its own anyway. It is to be included in another fully formed HTML document.

    That's That!

    I want to remind you that I have two other tutorials dealing with SSI Dates and Times and SSI File Returns. Take a look at them both. I think you'll find them useful.

    Good luck with these. I hope your server allows you to play with them!

    Enjoy!

    [ Can You Run SSI? ]
    [ Types of SSI ]
    [ The Include Command ]
    [ The File Argument ]
    [ The Virtual Argument ]
    [ The Included File ]

    SSI: Dates and Times



    Use these to jump around or read it all...
    [ Config and Echo ]
    [ The timefmt Argument ]
    [ The Codes ]
    [ Multiple Codes ]

    This is the second in a series of three tutorials on SSIs ( S erver S ide I ncludes). These are commands from the PERL language that allow you to include files and information right from the server.

    If you haven't already, please take the time to read the original SSI tutorial first.

    In that tutorial you'll get a little script that allows you to test your server to see if you're even able to play with these commands, and a lesson on the "include" command. It's best that you do read that first because I'm going to assume you have at this point and just bull forward.

    Bull, bull, bull...

    Config and Echo

    Let's talk about the basic format first. Once we have that, then the rest is a simple chart of what argument returns what. Here's the format: <!--#config timefmt="--" --> <!--#echo var="DATE_LOCAL" -->

    The format for these includes is quite rigid. You must keep it the same. Do not put in spaces where they don't now appear. HTML is flexible. This is not. The biggest mistake I make is not having a space just before the final two dashes at the end of the command lines. Make sure that's in there. You don't get error warnings with these commands. They simply fail to work and you can spend hours trying to figure out what's wrong when it's only a missing space.

    I guess the point I'm making is to not mess with the layout of the command line.

    That said, look at what we have here. It's actually two command lines, one after the other. The first command line denotes the time format and the second echoes it back. See that?

    Let me start with the second one because that's the one that requires the least amount of work. In fact, it requires no work. Leave it the way it is. The echo command should always have the var argument set to "DATE_LOCAL", in caps, with an underscore between the words.

    Every time you set an include to grab a date or a time, always follow that command with this echo command line so it echoes back and gets posted to the page.

    I think I've driven that point into the ground.

    The timefmt Argument

    Moving backward, we get to the first command line. That's the one that reads #config timefmt="--" .

    The leading hash mark (#) is required, keep it. The argument "timefmt=" is used every time you want to return a date or time. The big question is what you want returned. There are 21 choices, each identified by a percent mark, a one-letter code that goes in between the quotes following "timefmt=".

    The Codes

    The codes make little sense to me. They don't seem to represent what they return, so you'll need some kind of chart to keep it all straight. I have one below.

    I'll use the first code, %a, to demonstrate a command line. The code %a will return the abbreviated weekday name (Mon, Tue, Wed) depending on the current local. The command would look like this:

    <!--#config timefmt="%a" --> <!--#echo var="DATE_LOCAL" -->

         ...and here's what it gives you: Mon

    There's no need looking at the source code to see how I placed the command lines because they won't be there. Only the return provided by the server will display.

    Here are all 21 timefmt arguments, what you'll get, and an example.

    Argument You Get: It Looks Like:
    %a Abbreviated Weekday Name Mon
    %A Full Weekday Name Monday
    %b Abbreviated Month Name Apr
    %B Full Month Name April
    %c Preferred Date & Time Mon Apr 24 02:35:40 2006
    %d Day of Month as digit 24
    %H Hour Number (24-Hour Clock) 02
    %I Hour Number (12-Hour Clock) 02
    %j Day of the Year Number 114
    %m Month as digit 04
    %M Minute Number 04
    %p AM or PM AM
    %S Second Number 1145860540
    %U Week Number/Sunday as Day One 17
    %w Day of the Week Number 1
    %x Preferred Format without Time 04/24/06
    %X Preferred Format without Date 02:35:40
    %y Two-Digit Year Number 06
    %Y Four-Digit Year 2006
    %Z Time Zone EDT

    You might notice that some of the elements claim they represent the "preferred" format; "preferred" means the default settings of the server. It can differ from server to server.

    Notice also that these returns are from the server. If you are in one time zone and the server is in another, the time zone the server is in will be reflected in the returned values.

    Multiple Codes

    The codes above can be used one right after another to create a longer date/time stamp. Let's say you want something that looks like this: Wednesday, January 26, 2000

    You could set up an SSI that looks like this:

    <!--#config timefmt="%A, %B %d, %Y" --> <!--#echo var="DATE_LOCAL" -->

    See how one just followed the other? The commas are in there, too. You can make up any combination you want by just following one with the other, leaving spaces and putting commas where you want them. Very cool.

    That's That

    These are great includes. My school Webmaster uses them to death. Hopefully, you too can find a use for them.

    Keep in mind that I also have the original SSI include tutorial and the SSI tutorial on file returns .

    Enjoy!

    [ Config and Echo ]
    [ The timefmt Argument ]
    [ The Codes ]
    [ Multiple Codes ]

    SSI: File Returns



    Use these to jump around or read it all...
    [ The Echo Command ]
    [ The Flastmod Command ]
    [ The Fsize Command ]

    This is the third in a series of S erver S ide I nclude (SSI) tutorials. This tutorial will not delve into what SSI actually is or how it works, so you may want to read the original first. There you'll find a little script to test your server and information on how to use the Include command to include other documents in your current document. Plus, you'll be much more prepared for this tutorial.

    The Echo Command

    Really smart HTML Goodies readers will remember this command from the SSI Date and Times tutorial.

    In that tutorial we used the echo command in tandem with the "timefmt" argument to return dates and times. Here, I want to show you four more arguments that go along with the echo command.

    The first stands apart from the other three so I'll use it to show you the format:

    <!--#echo var="DATE_GMT" -->

    The DATE_GMT value returns Greenwich Mean Time from the server. That basically stands alone. The next three are used to return information about the current document (the document the command is sitting on).

    <!--#echo var="Document_Name" -->
    Returns the name of the document. <!--#echo var="Document_URI" -->
    Returns the path to the document plus its name. <!--#echo var="Last_Modified" -->
    Returns when the document was last posted to the server.

    Just plop the commands onto the page where you want them. That's easy enough. Moving along...

     

    The Flastmod Command

    The flastmod command is created by smooshing together the text "file last modified."

    This may sound much the same as the echo var="Last_Modified" above. It is, but with one major difference: The echo command only deals with the document it is sitting on, while the flastmod command will allow you to return data from any file. Here's the format:

    <!--#flastmod file="page.html" -->

    The argument is "file" and is pointing at the file to describe. If you want to point to a file sitting somewhere other than the current directory, just put in the full path:

    <!--#flastmod file="/dog/tree/page.html" -->

    The only downfall I've found is trying to attach to a file on another server. No good. The include should be on the same server.

    The Fsize Command

    Fsize means file size. The command works the same way as the flastmod, allowing you to attach it to any file on the server following this format: <!--#fsize file="page.html" -->

    The command returns the size of the file you point it toward. Try it with both HTML and image files.

    That's That

    Enjoy the includes. Hope you can find a good use for them.

    Enjoy!

    [ The Echo Command ]
    [ The Flastmod Command ]
    [ The Fsize Command ]

    HTACCESS FILES

    Most hosting companies will host multiple domains on one server, and all the domains use the same Web server software installed on that server. This presents a problem. What if two Webmasters using the same server need different Web server configurations? Apache addressed this by using .htaccess files. (Other Web-server software packages have similar functionality. If your host isn't using Apache, you'll have to ask them how to implement local configurations.)

    ==>

    Apache, like any other software, has configuration files. Your host edits these "global" configuration files to serve as a default for all of the sites hosted on the server. The .htaccess file (pronounced "h t access") acts as a "local" configuration file so that individual Websites can customize the configuration to suit their needs.

    ==>

    The .htaccess file is an ordinary text file that you can create using Notepad or any text editor and ftp it into your Web root directory. This file will contain the configuration statements (commands) to customize the Apache Web server software for your Website.
    Notice that the file name starts with a period. This is to indicate to the Linux/UNIX operating system that it is a "system file" that is used by a server application, not by a user of the system (such as an html file would be). However, with Windows, the period denotes a separator between a file's name and its' "extension". As a result, if you try and create a .htaccess file in Windows it won't have a name. To get around this, create a file called htaccess.txt, ftp that to the server, and then rename it to .htaccess once it's there.

    SSI Without .shtml

    In order to understand what this use of htaccess can do for you, you have to understand what SSI directives are. (SSI directives are covered in the How To Use Your CGI-BIN page.) You can put an SSI directive tag in your Web page, but that doesn't mean the server will look for it. Looking through an html file for SSI directives is called "parsing", and by default a server doesn't parse every html file. It only parses pages that have a .shtml extension.

    Dilemma:

    You want to start using SSI directives in your Web pages to call a script or display certain things on the pages. Your host requires that pages with SSI directives have a .shtml extension. However, over time all of your pages have been linked to and indexed by search engines using their current .html extensions. If you change the extensions to comply with your host, a lot of people will start getting 404 errors.

    htaccess to the rescue! Certain htaccess statements allow you to tell the server to parse certain pages that don't have a .shtml extension.

    If you created the htaccess.txt file above, simply add the statements given below to it and re-ftp/rename it. If you didn't, here are the steps:
       
  • Use a text editor to create an htaccess.txt file and enter the following statements into it:

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

    replacing .html with .htm if that's what you are using for your pages.

  • Save the file and ftp it (using ASCII mode) to your Web root directory (or whatever directory your index.html file is in).

  • Rename the htaccess.txt file on the server to .htaccess

  • Try it out by entering a URL for one of the pages that contains an SSI directive and see if it's working.
  • The above can be thought of as the "directory method" method for enabling SSI parsing because all files in the directory with the specified extension will be parsed, including files in any sub-directories. SSI parsing does have a small performance price due to all this parsing. If your site has a lot of traffic and a lot of pages that performance price could add up. What if you have a lot of traffic and a lot of pages but you only have a few files that you want parsed? Then you'd want to use XBitHack which is covered in the next section.

    ==>

    Not all hosts allow you to use a .htaccess file. They have to use an AllowOverride statement in one of the global configuration files. Ask your host, or a potential host, if they allow the use of .htaccess files. If so, also ask if they allow the use of XbitHack. If they so 'No' to the question of htaccess, pleading with them to enable it on your server may work, especially if you sound like you know what you're talking about (which this page will help you to do).

    A .htaccess file is a very powerful tool. You can use it to set up password-protected directories, change the way Apache responds to certain events, etc. The flip side of that is that you can really hose things up or give unintended access to visitors if you're not careful. You may want to try out your attempts with .htaccess during low-traffic times on your Website so that any problems can be corrected without affecting too many visitors.

    ==>

    Note also that the very fact that this is a very powerful tool may be reason enough for some hosting services not to allow you to use it. A hosting service sets up multiple "virtual" Web servers so multiple domains can be hosting on a single system (each domain having it's own virtual Web server). They do this by adding statements (aka directives) to the main Apache configuration file (named httpd.conf). When they add these virtual server directives they must include the directive to enable htaccess functionality. If you try the above and it doesn't work, chances are good your host doesn't have the htaccess function enabled.
    XBitHack (pronounced "X bit hack") is simply one of those htaccess configuration statements mentioned above. If you're not willing to put up with the performance costs of the "directory method" for enabling parsing of non-.shtml pages covered above, think of XBitHack as a "file method". This is because you can specify on a file-by-file basis which non-.shtml files get parsed.
    Using XBitHack for this "file method" has two steps:

    • turn on XBitHack by adding the statement to your .htaccess file
    • "flag" the html pages you want parsed by changing their permissions to something a little out of the ordinary
    If you created the htaccess.txt file above, simply add the statement given below to it and re-ftp/rename it to enable XBitHack. If your .htaccess file contains the AddType and AddHandler statements from above, REMOVE THEM. If you didn't create the file earlier, here are the steps to enabling XBitHack:

    1. Use a text editor to create an htaccess.txt file and enter the following statement into it:

      XBitHack on

    2. Save the file and ftp it (using ASCII mode) to your Web root directory (or whatever directory your index.html file is in).

    3. Rename the htaccess.txt file to .htaccess

    4. CHMOD the page files, and only the page files, that you want parsed (i.e. that will contain SSI directives) to 744 (instead of 644). This is what tells the server to parse the page.

    5. Try it out by entering a URL for one of the pages that contains an SSI directive and see if it's working.

      If it doesn't work, check your error log for a message like

      XBitHack not allowed here
    It is possible that your host allows htaccess but not XBitHack. If you don't find the above error, you'll have to contact your host's technical support operation. However, by knowing what htaccess and XBitHack are, you can ask them intelligent questions regarding your problem. When they realize you know what you are talking about, they will be less likely to feed you a line of BS. Also, don't be surprised if the support person you speak to doesn't know what you are talking about. First-line technical support and sales people are usually entry-level jobs in an organization. If you get the sense they don't know what you are talking about, ask to speak to a more senior support person who does.

    Apache Tutorial: INFORMATION ON Server Side Includes

    Apache Tutorial: Information on Server Side Includes

    This article deals with Server Side Includes, usually called simply SSI. In this article, I'll talk about configuring your server to permit SSI, and introduce some basic SSI techniques for adding dynamic content to your existing HTML pages.

    In the latter part of the article, we'll talk about some of the somewhat more advanced things that can be done with SSI, such as conditional statements in your SSI directives.

    What are SSI?

    SSI (Server Side Includes) are directives that are placed in HTML pages, and evaluated on the server while the pages are being served. They let you add dynamically generated content to an existing HTML page, without having to serve the entire page via a CGI program, or other dynamic technology.

    The decision of when to use SSI, and when to have your page entirely generated by some program, is usually a matter of how much of the page is static, and how much needs to be recalculated every time the page is served. SSI is a great way to add small pieces of information, such as the current time. But if a majority of your page is being generated at the time that it is served, you need to look for some other solution.

     

    Configuring your server to permit SSI

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

    Options +Includes

    This tells Apache that you want to permit files to be parsed for SSI directives. Note that most configurations contain multiple Options directives that can override each other. You will probably need to apply the Options to the specific directory where you want SSI enabled in order to assure that it gets evaluated last.

    Not just any file is parsed for SSI directives. You have to tell Apache which files should be parsed. There are 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 to 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.

    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

    A brief comment about what not to do. You'll occasionally see people recommending that you just tell Apache to parse all .html files for SSI, so that you don't have to mess with .shtml file names. These folks have perhaps not heard about XBitHack . 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.

    Of course, on Windows, there is no such thing as an execute bit to set, so that limits your options a little.

    In its default configuration, Apache does not send the last modified date or content length HTTP headers on SSI pages, because these values are difficult to calculate for dynamic content. This can prevent your document from being cached, and result in slower perceived client performance. There are two ways to solve this:

    1. Use the XBitHack Full configuration. This tells Apache to determine the last modified date by looking only at the date of the originally requested file, ignoring the modification date of any included files.
    2. Use the directives provided by mod_expires to set an explicit expiration time on your files, thereby letting browsers and proxies know that it is acceptable to cache them.

     

    Basic SSI directives

    SSI directives have the following syntax:

    <!--#element attribute=value attribute=value ... -->

    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.

    The element can be one of a number of things, and we'll talk some more about most of these in the next installment of this series. For now, here are some examples of what you can do with SSI

    Today's date

    <!--#echo var="DATE_LOCAL" -->

    The echo element just spits out the value of a variable. There are a number of standard variables, which include the whole set of environment variables that are available to CGI programs. Also, you can define your own variables with the set element.

    If you don't like the format in which the date gets printed, you can use the config element, with a timefmt attribute, to modify that formatting.

    <!--#config timefmt="%A %B %d, %Y" --> Today is <!--#echo var="DATE_LOCAL" -->

    Modification date of the file

    This document last modified <!--#flastmod file="index.html" -->

    This element is also subject to timefmt format configurations.

    Including the results of a CGI program

    This is one of the more common uses of SSI - to output the results of a CGI program, such as everybody's favorite, a ``hit counter.''

    <!--#include virtual="/cgi-bin/counter.pl" -->

    Additional examples

    Following are some specific examples of things you can do in your HTML documents with SSI.

    When was this document modified?

    Earlier, we mentioned that you could use SSI to inform the user when the document was most recently modified. However, the actual method for doing that was left somewhat in question. The following code, placed in your HTML document, will put such a time stamp on your page. Of course, you will have to have SSI correctly enabled, as discussed above.

    <!--#config timefmt="%A %B %d, %Y" --> This file last modified <!--#flastmod file="ssi.shtml" -->

    Of course, you will need to replace the ssi.shtml with the actual name of the file that you're referring to. This can be inconvenient if you're just looking for a generic piece of code that you can paste into any file, so you probably want to use the LAST_MODIFIED variable instead:

    <!--#config timefmt="%D" --> This file last modified <!--#echo var="LAST_MODIFIED" -->

    For more details on the timefmt format, go to your favorite search site and look for strftime() . The syntax is the same.

    Including a standard footer

    If you are managing any site that is more than a few pages, you may find that making changes to all those pages can be a real pain, particularly if you are trying to maintain some kind of standard look across all those pages.

    Using an include file for a header and/or a footer can reduce the burden of these updates. You just have to make one footer file, and then include it into each page with the include SSI command. The include element can determine what file to include with either the file attribute, or the virtual attribute. The file attribute is a file path, relative to the current directory . That means that it cannot be an absolute file path (starting with /), nor can it contain ../ as part of that path. The virtual attribute is probably more useful, and should specify a URL relative to the document being served. It can start with a /, but must be on the same server as the file being served.

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

    I'll frequently combine the last two things, putting a LAST_MODIFIED directive inside a footer file to be included. SSI directives can be contained in the included file, and includes can be nested - that is, the included file can include another file, and so on. ====>

    What else can I config?

    In addition to being able to config the time format, you can also config two other things.

    Usually, when something goes wrong with your SSI directive, you get the message

    [an error occurred while processing this directive]

    If you want to change that message to something else, you can do so with the errmsg attribute to the config element:

    <!--#config errmsg="[It appears that you don't know how to use SSI]" -->

    Hopefully, end users will never see this message, because you will have resolved all the problems with your SSI directives before your site goes live. (Right?)

    And you can config the format in which file sizes are returned with the sizefmt attribute. You can specify bytes for a full count in bytes, or abbrev for an abbreviated number in Kb or Mb, as appropriate.

    Executing commands

    I expect that I'll have an article some time in the coming months about using SSI with small CGI programs. For now, here's something else that you can do with the exec element. You can actually have SSI execute a command using the shell ( /bin/sh , to be precise - or the DOS shell, if you're on Win32). The following, for example, will give you a directory listing.

    <pre> <!--#exec cmd="ls" --> </pre>

    or, on Windows

    <pre> <!--#exec cmd="dir" --> </pre>

    You might notice some strange formatting with this directive on Windows, because the output from dir contains the string ``< dir >'' in it, which confuses browsers.

    Note that this feature is exceedingly dangerous, as it will execute whatever code happens to be embedded in the exec tag. If you have any situation where users can edit content on your web pages, such as with a ``guestbook'', for example, make sure that you have this feature disabled. You can allow SSI, but not the exec feature, with the IncludesNOEXEC argument to the Options directive.

    Advanced SSI techniques

    In addition to spitting out content, Apache SSI gives you the option of setting variables, and using those variables in comparisons and conditionals.

    Caveat

    Most of the features discussed in this article are only available to you if you are running Apache 1.2 or later. Of course, if you are not running Apache 1.2 or later, you need to upgrade immediately, if not sooner. Go on. Do it now. We'll wait.

    Setting variables

    Using the set directive, you can set variables for later use. We'll need this later in the discussion, so we'll talk about it here. The syntax of this is as follows:

    <!--#set var="name" value="Rich" -->

    In addition to merely setting values literally like that, you can use any other variable, including environment variables , or some of the variables we discussed above (like LAST_MODIFIED , for example) to give values to your variables. You will specify that something is a variable, rather than a literal string, by using the dollar sign ($) before the name of the variable.

    <!--#set var="modified" value="$LAST_MODIFIED" -->

    To put a literal dollar sign into the value of your variable, you need to escape the dollar sign with a backslash.

    <!--#set var="cost" value="\$100" -->

    Finally, if you want to put a variable in the midst of a longer string, and there's a chance that the name of the variable will run up against some other characters, and thus be confused with those characters, you can place the name of the variable in braces, to remove this confusion. (It's hard to come up with a really good example of this, but hopefully you'll get the point.)

    <!--#set var="date" value="${DATE_LOCAL}_${DATE_GMT}" -->

    Conditional expressions

    Now that we have variables, and are able to set and compare their values, we can use them to express conditionals. This lets SSI be a tiny programming language of sorts. mod_include provides an if , elif , else , endif structure for building conditional statements. This allows you to effectively generate multiple logical pages out of one actual page.

    The structure of this conditional construct is:

    <!--#if expr="test_condition" --> <!--#elif expr="test_condition" --> <!--#else --> <!--#endif -->

    A test_condition can be any sort of logical comparison - either comparing values to one another, or testing the ``truth'' of a particular value. (A given string is true if it is nonempty.) For a full list of the comparison operators available to you, see the mod_include documentation. Here are some examples of how one might use this construct.

    In your configuration file, you could put the following line:

    BrowserMatchNoCase macintosh Mac BrowserMatchNoCase MSIE InternetExplorer

    This will set environment variables ``Mac'' and ``InternetExplorer'' to true, if the client is running Internet Explorer on a Macintosh.

    Then, in your SSI-enabled document, you might do the following:

    <!--#if expr="${Mac} && ${InternetExplorer}" --> Apologetic text goes here <!--#else --> Cool JavaScript code goes here <!--#endif -->

    Not that I have anything against IE on Macs - I just struggled for a few hours last week trying to get some JavaScript working on IE on a Mac, when it was working everywhere else. The above was the interim workaround.

    Any other variable (either ones that you define, or normal environment variables) can be used in conditional statements. With Apache's ability to set environment variables with the SetEnvIf directives, and other related directives, this functionality can let you do some pretty involved dynamic stuff without ever resorting to CGI.

    Conclusion

    SSI is certainly not a replacement for CGI, or other technologies used for generating dynamic web pages. But it is a great way to add small amounts of dynamic content to pages, without doing a lot of extra work.

    The Best Way to Do Include Files!

    The easiest way, by far to include extra data in your pages, is to use "server side includes" in your HTML. Almost all web servers support this, except for free web hosting companies. This is overwhelmingly the preferred way to go. A minor variation on this theme is the use of PHP instead of traditional server side include syntax.

    For those who cannot use server side includes or PHP, we also present a client side method that requires only HTML and JavaScript. But it's ugly, because not everyone has JavaScript enabled. Those who do have it enabled might still have security restrictions that limit what it can do. And not everyone who does have JavaScript has a web browser that supports the required features... though the vast majority now do.

    Equally important, search engines probably won't see your client side includes. And that means that anything in that part of the page won't get indexed. That can hurt you if there is no alternative way to reach that content on your site. If you care about helping users find your site, you need to make sure there's a way to see all important content without relying on JavaScript.

    Here's the executive summary: if you can use server side includes, you should. If you're not sure, try them first before using the client side method.

    How to Use Server Side Includes

    Server side includes are a simple way to tell your web server to insert various things at various points in your HTML page. You can use them without major changes to your existing pages. However, some web servers require that you name your file .shtml rather than .html in order to enable the parsing of your file by the server in order to find server side include directives. If server side includes don't appear to work, try renaming the page with a .shtml file extension before you give up.

    Of course, server side includes only work when a web server is being used to access your pages. This is only an issue when testing your pages on your local hard drive. If this becomes a problem, it may be time to install a web server on your own computer, for local testing purposes. After all, Apache is free for Windows , and both free and standard in Linux and MacOS X.

    A simple server side include directive to include another file found in the same folder looks like this:

    <!--#include virtual="insertthisfile.html" -->

    include virtual and include file do almost the same thing. The difference is that include virtual takes a URL-style path, which is what you probably expect. include virtual can also execute CGI programs, if your web server supports that, and include their output. include file takes a file-system path, and cannot execute CGI programs. Both also accept relative paths, so for a simple case like the above they work the same. If you don't understand the difference between web paths and file system paths, use include virtual . There are many more server side include directives available; for example, you can easily insert the current date into your page.

    IF IT DOESN'T SEEM TO WORK, TRY NAMING YOUR FILE WITH A .shtml EXTENSION, instead of .html. Please do not ignore this tip and then email me asking why it doesn't work!

    For more information, see the Apache server side includes tutorial, which also covers how to configure the free Apache web server correctly with support for server side include directives. For information about enabling Server Side Includes in Microsoft IIS, consult Microsoft TechNet .

     

    How to Use PHP For Server Side Includes

    If your server is configured to support PHP but not server side includes, or you just prefer to use PHP everywhere, you can easily include fragments of HTML in your PHP page like this:

    <?php include("filename.html"); ?>

    This is essentially the same thing as server side includes, just using a different syntax. The PHP page that contains this directive must have a .php extension and the server must support PHP. If you don't know PHP, you probably want to use ordinary server side includes instead as described above.

    PHP include directives can also point at files on any web site using a full URL:

    <?php include("http://www.othersite.com/filename.html"); ?>

    Of course, you must not steal content from another web site without the express written permission of the owners. To do so is a copyright violation and may lead to legal action against you.

    How to Use Client Side Includes

    Until recently web browsers did not support any elegant way of including one HTML document seamlessly into the body of another. While frames and inline frames have been available for a long time, these are ways to insert an obviously separate, scrollable sub-document into the page. Generating part of your page using JavaScript code kept in a separate file has also been possible for quite a while, but this requires that parts of your HTML be kept in JavaScript form, which is a pain to deal with.

    With Firefox (on any system), Internet Explorer 5 and up (on Windows), and Apple's Safari browser (on MacOS X), the situation has improved. A new mechanism called XMLHTTP can be used to fetch XML documents "on the fly" from a JavaScript program. That includes fetching HTML files. And both of these browsers support inserting what we've fetched at any given point in the current page.

    But this isn't a miracle cure. The web browser still has to be Firefox (on any operating system), Safari (on MacOS X), or IE 5 or better on Windows. That's the vast majority of users, but it's not everyone. And some users will have JavaScript turned off for security reasons.

    VERY IMPORTANT: if you use this method with pages on your hard drive, not on a web server , the latest versions of Internet Explorer will warn the user that there is "active content" in the page and refuse to insert your included file unless the user goes out of their way to allow it. You won't have this problem once you move the page to a real web server. Then it becomes clear to Internet Explorer that the page and the included file are on the same web site, and that nothing sneaky is going on. OK, we've been warned, so how do we do it? By adding the following JavaScript code to the <head> element of the web page:

    <script>
    function clientSideInclude(id, url) {
       var req = false;
       // For Safari, Firefox, and other non-MS browsers
       if (window.XMLHttpRequest) {
         try {
           req = new XMLHttpRequest();
         } catch (e) {
           req = false;
         }
       } else if (window.ActiveXObject) {
         // For Internet Explorer on Windows
         try {
           req = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
           try {
             req = new ActiveXObject("Microsoft.XMLHTTP");
           } catch (e) {
             req = false;
           }
         }
       }
      var element = document.getElementById(id);
      if (!element) {
       alert("Bad id " + id +
        "passed to clientSideInclude." +
        "You need a div or span element " +
        "with this id in your page.");
       return;
      }
       if (req) {
         // Synchronous request, wait till we have it all
         req.open('GET', url, false);
         req.send(null);
         element.innerHTML = req.responseText;
       } else {
         element.innerHTML =
        "Sorry, your browser does not support " +
           "XMLHTTPRequest objects. This page requires " +
           "Internet Explorer 5 or better for Windows, " +
           "or Firefox for any system, or Safari. Other " +
           "compatible browsers may also exist.";
       }
    }
    </script>

    Now we have the power to include another file at any point in the web page. We do that by creating a simple "placeholder" HTML element, giving it an ID that JavaScript code can recognize, and then passing both that ID and the URL of the file we want to include at that point to our clientSideInclude JavaScript function.

    One tricky wrinkle: clientSideInclude doesn't always work unless the page has already been completely loaded. So we'll need to call it from the onLoad handler of the <body> element. That's the safest time to call because the browser has definitely parsed all of our HTML by then.

    So at the point in your page where you wish to insert the file includeone.html , which is found in the same folder as the page, you'll need to do this:

    <span id="includeone">
    </span>

    And at the beginning of the body of your page, you'll need to do this:

    <body onLoad="clientSideInclude('includeone', 'includeone.html');">

    Of course, a long, complicated onLoad handler can be very ugly. You can avoid that problem by moving the call (or calls!) to clientSideInclude to a function in a <script> element somewhere in the <head> element of the page. Then just call your function from onLoad .

    JavaScript code in the included file might not be executed by all browsers. One more reason why server-side include is always better if you can use it.

    You can make things even more elegant by moving the clientSideInclude function to a separate file, clientSideInclude.js , and including that in the <head> element of your page with a <script> element like this one:

    <script language="JavaScript" src="clientSideInclude.js">
    </script>

    Server-side include is still the best choice by far. But this method should be useful to those who don't have that option.

    What To Include, And What Not To Include

    Some users have asked whether the file that is being included needs to be a fully complete and standards-compliant HTML document. No, it doesn't. In fact, it shouldn't be. If you include one complete HTML document into another, you wind up with two head elements, two body elements, and so on, which is just plain wrong.

    Just think about it this way: what the web browser finally receives should be a complete, standards-compliant document. It doesn't matter what the pieces you assemble to create that document look like on the server. Only what ultimately reaches the web browser is important.

    Should I turn on SSI for all html files?

    This is generally not recommended for busy sites - Processing a .html that does not have SSI uses more resources than just serving the .html.

    You will just need to add the following to your .htaccess

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

    (if using .htm then change the .html to .htm or whatever is needed)

    Take a look at the documentation at Apache for more complete details.

     

    FAQ

    I read somewhere on your forums that using SSI (server side includes) impacts server speed if you're using HTML or HTM extensions (as opposed to using SHTML extensions).

    I'd like to use SSI for the repetitive headers, footers and navigation stuff that I use on my web pages. It would make maintaining the sites much easier.

    I've read elsewhere on the net that using SHTML extensions may impact "freshness" when the spiders visit the pages, and as such, it's better to stick with HTML extensions. I am concerned with SEO. I can't seem to find anything definitive on whether this is true or not. But for the moment, let's assume it's true and it's better to use HTM and HTML.

    If one had 6 to 12 primary pages that used the include statements, and there were an additional set of pages that didn't require the include statements, couldn't one just use "HTM" extensions for those primary pages that require the include statements, and the rest could be "HTML" extensions?

    In other words, if one could use an "AddHandler server-parsed.htm" in a ".htaccess" file, how much of a "hit" is there on the server? (I presume this is what you have to do to make SSI work - correct me if I'm wrong.)

    Are you burning up more "bandwidth" using SSI with HTM and HTML extensions i.e. all pages are parsed each time the site is accessed?

    When the site is accessed, are all the pages with HTM extensions automatically read? Or perhaps one could move those files not requiring SSI to a subdirectory?

    Am I right to presume using SSI with HTM impacts the time it takes to serve the page to the user? If so, what kind of time are we talking about? Milliseconds?

    ==>

    Answer To FAQ:

    Anything which needs to be processed before serving up the page to the browser will take more time simply because the file needs to be run through the cpu first and then the output is sent out. How long this takes really depends on a couple of factors--what you are processing and how big of file your are processing.

    If you are just inserting a header or footer then you will probably not notice the impact. If you are parsing different banners each time then it will take longer. During this process you are not using more bandwidth because bandwidth is calculated as what you are ultimately transferring out to the browser not what you processing on the server.

    As for the question about all htm pages processed when someone visits--this is generally not true. The only page sent to the browser is the page requested. Now there are browsers and other programs which grab everything but they generally are used very much anymore.

    If you need more technical information about SSI check out this programmers forum--they have a lot of information about all aspects of programming:

    http://forums.devshed.com/

    FAQ: Tell Me More About SSI?

    Server side includes are a powerful feature of the Apache 1.2
    web server (which we use). SSI lets you include the contents
    of one file (or even the output of a CGI) within another web
    page.

    If you are a Non-Virtual account owner, the following will work
    automatically. If you are a Virtual Domain customer, you must
    create a text file in your root directory called '.htaccess'.
    Use a text editor like Notepad.

    In this file place the following line:

    XBitHack full

    Make sure to upload it in ASCII mode. WS_FTP will probably try
    to upload it in BINARY, so make sure to choose ASCII and shut
    off AUTO. These choices are at the bottom of the WS_FTP screen.

    The most frequent use of SSI is to add a standard "footer" to
    the bottom of each of your web pages, without having to include
    the footer code in each page. Instead a line like the following
    would be used where you want your footer:

    <!--#include virtual="footer.htm" -->

    Where "footer.htm" is the name of the file that contains the
    HTML of the footer you wish to appear in your web page.
    'footer.htm' must reside in the same directory as the calling
    page for this example.

     

    To make SSI work, the server must know to look for these
    special lines of code. So, you must either make your web page
    end with the extension .shtml -OR- turn on the EXECUTE bit of the
    file permissions. This is called using the Xbit Hack.

    In telnet this command would be: chmod 744 filename.htm

    From WS_FTP, choose the file, then right click on the file and
    choose 'chmod (UNIX)' from the menu. Then under Owner, check
    Execute.

    Setting the Group Execute bit to ON also allows the pages to be
    cached by browsers. Thus, the server doesn't have to re-
    include the called pages. This works very well for things like
    footers, but is not good for pages that include the output of
    a CGI program, or other possibly changing output. The telnet
    command would be: chmod 754 filename.htm

    FAQ ON .SHTML

    I am re working my personal website, I want to convert to shtml. My question is, if I do that, what happens to all my links from other sites, and my google stuff? How do I or should I use redirects? Can you do a blanket redirect using what I used to refer to wildcard properties?

    Like http://www.designbyatfb.com/ *.*.html to

    http://www.designbyatfb.com/ *.*.shtml

    is that a stupid question?

    Redirects in .htaccess can't have wildcards. You can direct a whole directory to a different directory, but you can't use standard redirects to change all extensions to a different extension.

    That leaves you with at least three options:

    List all pages on the site with the old extension redirected to the new extension:/oldpage.html http: // {domain}.com/oldpage.shtml

    Use mod-rewrite to change the page name by wildcard. (But this is a very wierd bit of Unix hacker-ware that's obnoxiously difficult to use.)

    Check to see if your server supports what is called the "x-bit hack". If it does support it, you won't have to change the page extension. Instead, just mark the file with permission bits 744 which sets the owner-execute permission on the file. When an Apache server with that feature enabled encounters a ".html" file with the owner execute bit set, it will process that file for SSI.

    XBitHack directive

    Syntax: XBitHack on|off|full
    Default: XBitHack off
    Context: server config, virtual host, directory, .htaccess
    Override: Options
    Status: Base
    Module: mod_include

    The XBitHack directives controls the parsing of ordinary html documents. This directive only affects files associated with the MIME type text/html. XBitHack can take on the following values:

    off
    No special treatment of executable files.
    on
    Any file that has the user-execute bit set will be treated as a server-parsed html document.
    full
    As for on but also test the group-execute bit. If it is set, then set the Last-modified date of the returned file to be the last modified time of the file. If it is not set, then no last-modified date is sent. Setting this bit allows clients and proxies to cache the result of the request.

    Note: you would not want to use this, for example, when you #include a CGI that produces different output on each hit (or potentially depends on the hit).

    Another question, if you please...

    Which should be done first, htaccess redirects or uploading pages?

    Add these lines to your .htaccess file

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

    you can tell theserver to treat .html as if it were .shtml . In Cpanel > Apache Handlers, you add one that specifies:

    Extension: .html
    Handler: server-parsed

    This works fine, but it's not so portable if you should change hosting environment.

    Actually you will see it adds a line to your .htaccess file that you have in the root folder.

    It's very portable - as long as you have a .htaccess file. The solutions offered all involved using a .htaccess file. That makes it as good a solution as using redirects without the extra overhead of the redirect.
    The only one that isn't necessarily portable is using the x-bit feature. That one can't be done with .htaccess alone, but requires a root-mode configuration of the server.

    But it isn't that much different than using the AddHandler technique in .htaccess. The one difference is that using the x-bit-hack doesn't cause all .html files to be processed for SSI directives as would happen with the AddHandler technique. Instead, only those pages with the x-bit set are processed that way. (Of course, the server has to check every page for that protection bit, so it probably isn't all that much more efficient.)

    I don't recommend relying too much on this .htaccess file for all times. Too easy to accidentally overwrite it or mess it up.

    Having redirects is only needed for search engines that have cached images and addresses. It does not affect the basic functioning of the site. Relying on .htaccess for that I think is a bit risky.

    The only trouble with the x-bit solution is that you have to manually change the permissions for every file you want to be handled that way. That could be dozens or more. The beauty of doing it with the apache handler is that it only takes a couple of minutes and you don't have to rename any of your files.

    There's more than just the search engines that you have to think about. What about all the people who may have bookmarked pages on your site or links from other sites, like this forum? And, it's not just the files they have cached, it's the links they have in their index which can be there seemingly forever.

    There is an obvious need for a method to redirect to new files. I'm not aware of any method that will work as well and as reliably as the .htaccess file. I use it to redirect from my old urls which were mydomain.com/blog/ to mydomain.com/ as you can see at http://www.jonra.com/blog/index.html

    The only ways I am aware of dealing with issues of this type are:

    1) Leave the old pages up and use the meta refresh to redirect users (poor solution)
    2) Leave the old pages up and use javascript to redirect (very poor solution)
    3) Use the x-bit hack that Robin suggested (requires changing permissions for each file for which you want this to work and requires the hack to be enabled by the server manager)
    4) Writing individual redirects in .htaccess for each individual file (impractical)
    5) Use rewritecond with regular expressions to handle it with wildcards (tricky)
    6) use the addhandler bit in the .htaccess file

    FAQ:

    So you use the .htaccess file for redirects. What do you do if you have 200 pages you want to redirect?

     

    I'd have never reached 200 pages without already using SSI, would I? I'm much too lazy to have ever tediously coded 200 pages one by one.

    I think that from my very first site, bad as it was, by the time I got to have about 10 pages I became exceedingly iritated at making the same stupid changes in each of them every time I needed a tweak (or fix a common bug) and I actively sought information on ways to have what I later learned was called SSI. My only beef was that I couldn't view the pages properly on my own pc as I didn't have Apache installed until just recently.

    FAQ:

    I cant seem to get server side includes to work on my apache web server on os X (jaguar 10.2.6). I have read many articles and tried various metods but no luck. ( i was successful getting PHP running ).

    I have changed my http.conf file to include:
    AddType text/html .shtml
    AddHandler server-parsed .shtml
    AddHandler server-parsed .html

    I have also set "Options Includes" inside
    <Directory "Library/WebServer/Documents" >
    I have also tried using .htaccess files and XBit Hack, but all to no avail so I am stumped.

    Here are some things to look for:

    1) Are you sure you have the Option Includes in the correct place?

    2) Is mod_includes enabled? (I think that is the name).

    Apache Web Server (v1.3.x; v2.0) (http://www.apache.org)

    1. Open httpd.conf (usually in /etc)
    2. Locate the <DIRECTORY> directive in the httpd.conf file where you want to enable SSI.
    3. Add the following line inside the <DIRECTORY> section:

    AddType text/x-server-parsed-html .shtml
    4. This next bit gets tricky. You have to tell the server where to expect the SSI's and what SSI's are allowed to do.

    a. To enable SSI's to be included in the page use:

    Options +Includes

    b. To enable SSI's to execute external programs on the server use:

    Options ExecCGI

    c. To enable BOTH includes and CGI's, use:

    Options Includes ExecCGI
    5. Once you've made the appropriate changes, save the httpd.conf file.
    6. Restart the Apache server.
    7. Add your SSI directives to one or more web files.
    8. Change the extension of those files from .htm or .html to .shtml.

    You should not use .html as the file extension identifier for SSI directives because it increases server load for all page hits. Server Side Includes take up processing power, so enabling SSI in all .htm and .html web pages is a bad idea. If you enable SSI for all web pages, you cause Apache to parse all files for SSI directives before delivering them, which adds CPU cycles to each web page hit.

    X-bit Hack

    For the Apache server, there is also the X-Bit hack. The idea behind the X-bit hack is to allow the Apache server to recognize executables by their permissions. Files with the execute bit set are treated as executables by the Apache server. The X-bit hack is disabled by default.

    See the Apache's Server Side Include page for more information. You can also refer to the NCSA httpd server documentation since Apache is simply the NCSA server with patches applied (that's how the Apache ["a-patchy"] server got its name).

    Microsoft Internet Information Server

    WARNING: Make certain you are using the latest Windows Service Pack, and the latest patch level for IIS. Note that Microsoft does NOT support a full NCSA-compliant HTTPd implmentation; thus, it does NOT support SSI directves fully.

    * IIS 4.0 (Windows NT 4.0)
    * IIS 5.0 (Windows 2000)

    Server Side Includes are already enabled on Microsoft's servers by default, making an IIS server less secure than the Apache server in the default configuration (and slower as well). All you have to do is add the directives to your web pages and rename them *.shtml.


    REMEMBER: Pages that use SSI need to be named in a way that tells the server to look for SSI commands. Usually this involves using .SHTML as the extension instead of .HTML. If you have an accommodating ISP, ask them to turn on the xbit hack. This allows you to set the permissions of any file to be executable (Unix CHMOD 755), and regardless of the file extension, SSI commands can be included. This way, you don't have to rename all your files to .SHTML, you just set the proper permissions on your HTML files.

    How to use chmod command