This module allows the server to be extended with scripts written in the
Lua programming language. The extension points (hooks) available with
More information on the Lua programming language can be found at the the Lua website.
This module holds a great deal of power over httpd, which is both a strength and a potential security risk. It is not recommended that you use this module on a server that is shared with users you do not trust, as it can be abused to change the internal workings of httpd.
The basic module loading directive is
mod_lua
provides a handler named lua-script
,
which can be used with a
This will cause mod_lua
to handle requests for files
ending in .lua
by invoking that file's
handle
function.
For more flexibility, see
In the Apache HTTP Server API, the handler is a specific kind of hook
responsible for generating the response. Examples of modules that include a
handler are
mod_lua
always looks to invoke a Lua function for the handler, rather than
just evaluating a script body CGI style. A handler function looks
something like this:
This handler function just prints out the uri or form encoded arguments to a plaintext page.
This means (and in fact encourages) that you can have multiple handlers (or hooks, or filters) in the same script.
The authz provider is normally called before authentication. If it needs to
know the authenticated user name (or if the user will be authenticated at
all), the provider must return apache2.AUTHZ_DENIED_NO_USER
.
This will cause authentication to proceed and the authz provider to be
called a second time.
The following authz provider function takes two arguments, one ip address and one user name. It will allow access from the given ip address without authentication, or if the authenticated user matches the second argument:
The following configuration registers this function as provider
foo
and configures it for URL /
:
Hook functions are how modules (and Lua scripts) participate in the processing of requests. Each type of hook exposed by the server exists for a specific purpose, such as mapping requests to the file system, performing access control, or setting mime types:
Hook phase | mod_lua directive | Description |
---|---|---|
Quick handler | This is the first hook that will be called after a request has been mapped to a host or virtual host | |
Translate name | This phase translates the requested URI into a filename on the
system. Modules such as |
|
Map to storage | This phase maps files to their physical, cached or external/proxied storage. It can be used by proxy or caching modules | |
Check Access | This phase checks whether a client has access to a resource. This phase is run before the user is authenticated, so beware. | |
Check User ID | This phase it used to check the negotiated user ID | |
Check Authorization | This phase authorizes a user based on the negotiated credentials, such as user ID, client certificate etc. | |
Check Type | This phase checks the requested file and assigns a content type and a handler to it | |
Fixups | This is the final "fix anything" phase before the content handlers are run. Any last-minute changes to the request should be made here. | |
Content handler | fx. .lua files or through |
This is where the content is handled. Files are read, parsed, some are run, and the result is sent to the client |
Logging | Once a request has been handled, it enters several logging phases, which logs the request in either the error or access log. Mod_lua is able to hook into the start of this and control logging output. |
Hook functions are passed the request object as their only argument
(except for LuaAuthzProvider, which also gets passed the arguments from
the Require directive).
They can return any value, depending on the hook, but most commonly
they'll return OK, DONE, or DECLINED, which you can write in Lua as
apache2.OK
, apache2.DONE
, or
apache2.DECLINED
, or else an HTTP status code.
The request_rec is mapped in as a userdata. It has a metatable which lets you do useful things with it. For the most part it has the same fields as the request_rec struct, many of which are writable as well as readable. (The table fields' content can be changed, but the fields themselves cannot be set to different tables.)
Name | Lua type | Writable | Description |
---|---|---|---|
allowoverrides |
string | no | The AllowOverride options applied to the current request. |
ap_auth_type |
string | no | If an authentication check was made, this is set to the type
of authentication (f.x. basic ) |
args |
string | yes | The query string arguments extracted from the request
(f.x. foo=bar&name=johnsmith ) |
assbackwards |
boolean | no | Set to true if this is an HTTP/0.9 style request
(e.g. GET /foo (with no headers) ) |
auth_name |
string | no | The realm name used for authorization (if applicable). |
banner |
string | no | The server banner, f.x. Apache HTTP Server/2.4.3 openssl/0.9.8c |
basic_auth_pw |
string | no | The basic auth password sent with this request, if any |
canonical_filename |
string | no | The canonical filename of the request |
content_encoding |
string | no | The content encoding of the current request |
content_type |
string | yes | The content type of the current request, as determined in the
type_check phase (f.x. image/gif or text/html ) |
context_prefix |
string | no | |
context_document_root |
string | no | |
document_root |
string | no | The document root of the host |
err_headers_out |
table | no | MIME header environment for the response, printed even on errors and persist across internal redirects |
filename |
string | yes | The file name that the request maps to, f.x. /www/example.com/foo.txt. This can be changed in the translate-name or map-to-storage phases of a request to allow the default handler (or script handlers) to serve a different file than what was requested. |
handler |
string | yes | The name of the handler that should serve this request, f.x.
lua-script if it is to be served by mod_lua. This is typically set by the
|
headers_in |
table | yes | MIME header environment from the request. This contains headers such as Host,
User-Agent, Referer and so on. |
headers_out |
table | yes | MIME header environment for the response. |
hostname |
string | no | The host name, as set by the Host: header or by a full URI. |
is_https |
boolean | no | Whether or not this request is done via HTTPS |
is_initial_req |
boolean | no | Whether this request is the initial request or a sub-request |
limit_req_body |
number | no | The size limit of the request body for this request, or 0 if no limit. |
log_id |
string | no | The ID to identify request in access and error log. |
method |
string | no | The request method, f.x. GET or POST . |
notes |
table | yes | A list of notes that can be passed on from one module to another. |
options |
string | no | The Options directive applied to the current request. |
path_info |
string | no | The PATH_INFO extracted from this request. |
port |
number | no | The server port used by the request. |
protocol |
string | no | The protocol used, f.x. HTTP/1.1 |
proxyreq |
string | yes | Denotes whether this is a proxy request or not. This value is generally set in the post_read_request/translate_name phase of a request. |
range |
string | no | The contents of the Range: header. |
remaining |
number | no | The number of bytes remaining to be read from the request body. |
server_built |
string | no | The time the server executable was built. |
server_name |
string | no | The server name for this request. |
some_auth_required |
boolean | no | Whether some authorization is/was required for this request. |
subprocess_env |
table | yes | The environment variables set for this request. |
started |
number | no | The time the server was (re)started, in seconds since the epoch (Jan 1st, 1970) |
status |
number | yes | The (current) HTTP return code for this request, f.x. 200 or 404 . |
the_request |
string | no | The request string as sent by the client, f.x. GET /foo/bar HTTP/1.1 . |
unparsed_uri |
string | no | The unparsed URI of the request |
uri |
string | yes | The URI after it has been parsed by httpd |
user |
string | yes | If an authentication check has been made, this is set to the name of the authenticated user. |
useragent_ip |
string | no | The IP of the user agent making the request |
The request_rec object has (at least) the following methods:
a
:
local process = r:scoreboard_process(1)
r:puts("Server 1 has PID " .. process.pid)
b
, in process a
:
local thread = r:scoreboard_worker(1, 1)
r:puts("Server 1's thread 1 has thread ID " .. thread.tid .. " and is in " .. thread.status .. " status")
A package named apache2
is available with (at least) the following contents.
(Other HTTP status codes are not yet implemented.)
Filter functions implemented via
Mod_lua implements a simple database feature for querying and running commands on the most popular database engines (mySQL, PostgreSQL, FreeTDS, ODBC, SQLite, Oracle) as well as mod_dbd.
The example below shows how to acquire a database handle and return information from a table:
To utilize mod_dbd
as the database type, or leave the field blank:
The database object returned by dbacquire
has the following methods:
Normal select and query from a database:
Using prepared statements (recommended):
Escaping values, closing databases etc:
The result set returned by db:select
or by the prepared statement functions
created through db:prepare
can be used to
fetch rows synchronously or asynchronously, depending on the row number specified:
result(0)
fetches all rows in a synchronous manner, returning a table of rows.
result(-1)
fetches the next available row in the set, asynchronously.
result(N)
fetches row number N
, asynchronously:
One can construct a function that returns an iterative function to iterate over all rows in a synchronous or asynchronous way, depending on the async argument:
Database handles should be closed using database:close()
when they are no longer
needed. If you do not close them manually, they will eventually be garbage collected and
closed by mod_lua, but you may end up having too many unused connections to the database
if you leave the closing up to mod_lua. Essentially, the following two measures are
the same:
Although the standard query
and run
functions are freely
available, it is recommended that you use prepared statements whenever possible, to
both optimize performance (if your db handle lives on for a long time) and to minimize
the risk of SQL injection attacks. run
and query
should only
be used when there are no variables inserted into a statement (a static statement).
When using dynamic statements, use db:prepare
or db:prepared
.
Specify the base path which will be used to evaluate all relative paths within mod_lua. If not specified they will be resolved relative to the current working directory, which may not always work well for a server.
Specify the life cycle scope of the Lua interpreter which will be used by handlers in this "Directory." The default is "once"
min
and max
arguments
specify the minimum and maximum number of Lua states to keep in the
pool.
Generally speaking, the thread
and server
scopes
execute roughly 2-3 times faster than the rest, because they don't have to
spawn new Lua states on every request (especially with the event MPM, as
even keepalive requests will use a new thread for each request). If you are
satisfied that your scripts will not have problems reusing a state, then
the thread
or server
scopes should be used for
maximum performance. While the thread
scope will provide the
fastest responses, the server
scope will use less memory, as
states are pooled, allowing f.x. 1000 threads to share only 100 Lua states,
thus using only 10% of the memory required by the thread
scope.
This directive matches a uri pattern to invoke a specific handler function in a specific file. It uses PCRE regular expressions to match the uri, and supports interpolating match groups into both the file path and the function name. Be careful writing your regular expressions to avoid security issues.
This would match uri's such as /photos/show?id=9 to the file /scripts/photos.lua and invoke the handler function handle_show on the lua vm after loading that file.
This would invoke the "handle" function, which is the default if no specific function name is provided.
Add a path to lua's module search path. Follows the same conventions as lua. This just munges the package.path in the lua vms.
Add a path to lua's shared library search path. Follows the same conventions as lua. This just munges the package.cpath in the lua vms.
Specify the behavior of the in-memory code cache. The default is stat, which stats the top level script (not any included ones) each time that file is needed, and reloads it if the modified time indicates it is newer than the one it has already loaded. The other values cause it to keep the file cached forever (don't stat and replace) or to never cache the file.
In general stat or forever is good for production, and stat or never for development.
Add a hook (at APR_HOOK_MIDDLE) to the translate name phase of request processing. The hook function receives a single argument, the request_rec, and should return a status code, which is either an HTTP error code, or the constants defined in the apache2 module: apache2.OK, apache2.DECLINED, or apache2.DONE.
For those new to hooks, basically each hook will be invoked until one of them returns apache2.OK. If your hook doesn't want to do the translation it should just return apache2.DECLINED. If the request should stop processing, then return apache2.DONE.
Example:
This directive is not valid in
The optional arguments "early" or "late" control when this script runs relative to other modules.
Just like LuaHookTranslateName, but executed at the fixups phase
This simple logging hook allows you to run a function when httpd enters the
logging phase of a request. With it, you can append data to your own logs,
manipulate data before the regular log is written, or prevent a log entry
from being created. To prevent the usual logging from happening, simply return
apache2.DONE
in your logging handler, otherwise return
apache2.OK
to tell httpd to log as normal.
Example:
Like
This directive provides a hook for the type_checker phase of the request processing. This phase is where requests are assigned a content type and a handler, and thus can be used to modify the type and handler based on input:
Invoke a lua function in the auth_checker phase of processing a request. This can be used to implement arbitrary authentication and authorization checking. A very simple example:
The optional arguments "early" or "late" control when this script runs relative to other modules.
Add your hook to the access_checker phase. An access checker hook function usually returns OK, DECLINED, or HTTP_FORBIDDEN.
The optional arguments "early" or "late" control when this script runs relative to other modules.
Not Yet Implemented
By default, if LuaHook* directives are used in overlapping Directory or Location configuration sections, the scripts defined in the more specific section are run after those defined in the more generic section (LuaInherit parent-first). You can reverse this order, or make the parent context not apply at all.
In previous 2.3.x releases, the default was effectively to ignore LuaHook* directives from parent configuration sections.
This phase is run immediately after the request has been mapped to a virtal host,
and can be used to either do some request processing before the other phases kick
in, or to serve a request without the need to translate, map to storage et cetera.
As this phase is run before anything else, directives such as
This directive is not valid in
After a lua function has been registered as authorization provider, it can be used
with the
Provides a means of adding a Lua function as an input filter.
As with output filters, input filters work as coroutines,
first yielding before buffers are sent, then yielding whenever
a bucket needs to be passed down the chain, and finally (optionally)
yielding anything that needs to be appended to the input data. The
global variable bucket
holds the buckets as they are passed
onto the Lua script:
The input filter supports denying/skipping a filter if it is deemed unwanted:
See "Modifying contents with Lua filters" for more information.
Provides a means of adding a Lua function as an output filter.
As with input filters, output filters work as coroutines,
first yielding before buffers are sent, then yielding whenever
a bucket needs to be passed down the chain, and finally (optionally)
yielding anything that needs to be appended to the input data. The
global variable bucket
holds the buckets as they are passed
onto the Lua script:
As with the input filter, the output filter supports denying/skipping a filter if it is deemed unwanted:
When a Lua filter is used as the underlying provider via the
See "Modifying contents with Lua filters" for more information.