Frederic Cambus

Home · Archives · Text Mode · GitHub · Twitter · RSS

Nginx and Server Side Includes

· Nginx

Server Side Includes are an interesting way to embed content dynamically into static files. It can be particularly useful to inject information about the visitor or to add headers, footers or any file containing data changing over time.

Please note, however, that Nginx does not implement the full SSI specification yet. More information about what is currently supported can be found in the ngxhttpssi_module documentation.

To enable SSI, the following directive must be added in the http, server or location block:

ssi on;

Here is an example HTML snippet with SSI directives, showing how to echo variables and include content from other files:

<h2>Visitor information</h2>

<p>Visitor IP address: <!--#echo var="REMOTE_ADDR" --></p>
<p>Visitor User agent: <!--#echo var="HTTP_USER_AGENT" --></p>

<h2>Server information</h2>

<p>Server local time: <!--#echo var="DATE_LOCAL" --></p>
<p>Server time (GMT): <!--#echo var="DATE_GMT" --></p>

<p>Server uptime (refreshed every minute): <!--#include file="uptime.txt" --></p>

<h2>Fortune of the day</h2>

<!--#include file="fortune.txt" -->

In order to populate fortune.txt and uptime.txt, we can use Cron and refresh files content as required. For even more fun, we can also use cowsay together with fortune.

Let's add the following entries to the Crontab:

* * * * * uptime > /path/to/htdocs/uptime.txt
0 0 * * * /usr/games/fortune | /usr/games/cowsay -f tux > /path/to/htdocs/fortune.txt

Finally, here is the resulting output when accessing the page using Lynx:

Visitor information

   Visitor IP address:

   Visitor User agent: Lynx/2.8.8rel.2 libwww-FM/2.14 SSL-MM/1.4.1 OpenSSL/1.0.1h

Server information

   Server local time: Sunday, 21-Sep-2014 18:55:49 CEST

   Server time (GMT): Sunday, 21-Sep-2014 16:55:49 GMT

   Server uptime: 18:55:01 up 52 days, 7:50, 3 users, load average: 0.13, 0.19, 0.22

Fortune of the day

/ In most countries selling harmful      \
| things like drugs is punishable. Then  |
| howcome people can sell Microsoft      |
| software and go unpunished?            |
|                                        |
\ -- Hasse Skrifvars,, /
       |o_o |
       |:_/ |
      //   \ \
     (|     | )
    /'\_   _/`\