mod_lua Provides Lua hooks into various portions of the httpd request processing Experimental mod_lua.c lua_module 2.3 and later

This module allows the server to be extended with scripts written in the Lua programming language. The extension points (hooks) available with mod_lua include many of the hooks available to natively compiled Apache HTTP Server modules, such as mapping requests to files, generating dynamic responses, access control, authentication, and authorization

More information on the Lua programming language can be found at the the Lua website.

mod_lua is still in experimental state. Until it is declared stable, usage and behavior may change at any time, even between stable releases of the 2.4.x series. Be sure to check the CHANGES file before upgrading. Warning

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.

Basic Configuration

The basic module loading directive is

LoadModule lua_module modules/mod_lua.so

mod_lua provides a handler named lua-script, which can be used with an AddHandler directive:

AddHandler lua-script .lua

This will cause mod_lua to handle requests for files ending in .lua by invoking that file's handle function.

For more flexibility, see LuaMapHandler.

Writing Handlers

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_proxy, mod_cgi, and mod_status.

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:

example.lua
-- example handler require "string" --[[ This is the default method name for Lua handlers, see the optional function-name in the LuaMapHandler directive to choose a different entry point. --]] function handle(r) r.content_type = "text/plain" r:puts("Hello Lua World!\n") if r.method == 'GET' then for k, v in pairs( r:parseargs() ) do r:puts( string.format("%s: %s\n", k, v) ) end elseif r.method == 'POST' then for k, v in pairs( r:parsebody() ) do r:puts( string.format("%s: %s\n", k, v) ) end else r:puts("Unsupported HTTP method " .. r.method) end end

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.

Writing Authorization Providers

mod_authz_core provides a high-level interface to authorization that is much easier to use than using into the relevant hooks directly. The first argument to the Require directive gives the name of the responsible authorization provider. For any Require line, mod_authz_core will call the authorization provider of the given name, passing the rest of the line as parameters. The provider will then check authorization and pass the result as return value.

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:

authz_provider.lua
require 'apache2' function authz_check_foo(r, ip, user) if r.useragent_ip == ip then return apache2.AUTHZ_GRANTED elseif r.user == nil then return apache2.AUTHZ_DENIED_NO_USER elseif r.user == user then return apache2.AUTHZ_GRANTED else return apache2.AUTHZ_DENIED end end

The following configuration registers this function as provider foo and configures it for URL /:

LuaAuthzProvider foo authz_provider.lua authz_check_foo <Location /> Require foo 10.1.2.3 john_doe </Location>
Writing Hooks

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 purposes such as mapping requests to the filesystem, performing access control, or setting mimetypes:

Hook phase mod_lua directive Description
Quick handler LuaQuickHandler This is the first hook that will be called after a request has been mapped to a host or virtual host
Translate name LuaHookTranslateName This phase translates the requested URI into a filename on the system. Modules such as mod_alias and mod_rewrite operate in this phase.
Map to storage LuaHookMapToStorage This phase maps files to their physical, cached or external/proxied storage. It can be used by proxy or caching modules
Check Access LuaHookAccessChecker 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 LuaHookCheckUserID This phase it used to check the negotiated user ID
Check Authorization LuaHookAuthChecker or LuaAuthzProvider This phase authorizes a user based on the negotiated credentials, such as user ID, client certificate etc.
Check Type LuaHookTypeChecker This phase checks the requested file and assigns a content type and a handler to it
Fixups LuaHookFixups 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 LuaMapHandler This is where the content is handled. Files are read, parsed, some are run, and the result is sent to the client
Logging (none) Once a request has been handled, it enters several logging phases, which logs the request in either the error or access log

Hook functions are passed the request object as their only argument. 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.

translate_name.lua
-- example hook that rewrites the URI to a filesystem path. require 'apache2' function translate_name(r) if r.uri == "/translate-name" then r.filename = r.document_root .. "/find_me.txt" return apache2.OK end -- we don't care about this URL, give another module a chance return apache2.DECLINED end
translate_name2.lua
--[[ example hook that rewrites one URI to another URI. It returns a apache2.DECLINED to give other URL mappers a chance to work on the substitution, including the core translate_name hook which maps based on the DocumentRoot. Note: Use the early/late flags in the directive to make it run before or after mod_alias. --]] require 'apache2' function translate_name(r) if r.uri == "/translate-name" then r.uri = "/find_me.txt" return apache2.DECLINED end return apache2.DECLINED end
Data Structures
request_rec

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 writeable 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
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) )
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 AddHandler or SetHandler directives, but could also be set via mod_lua to allow another handler to serve up a specific request that would otherwise not be served by it.
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
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.
path_info string no The PATH_INFO extracted from this 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.
subprocess_env table yes The environment variables set for this request.
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 has (at least) the following methods:

r:addoutputfilter(name|function) -- add an output filter r:parseargs() -- returns a Lua table containing the request's query string arguments r:parsebody() -- parse any POST data in the request and return it as a Lua table r:puts("hello", " world", "!") -- print to response body r:write("a single string") -- print to response body r:escape_html("<html>test</html>") -- Escapes HTML code and returns the escaped result
Logging Functions -- examples of logging messages
r:trace1("This is a trace log message") -- trace1 through trace8 can be used
r:debug("This is a debug log message")
r:info("This is an info log message")
r:notice("This is an notice log message")
r:warn("This is an warn log message")
r:err("This is an err log message")
r:alert("This is an alert log message")
r:crit("This is an crit log message")
r:emerg("This is an emerg log message")
apache2 Package

A package named apache2 is available with (at least) the following contents.

apache2.OK
internal constant OK. Handlers should return this if they've handled the request.
apache2.DECLINED
internal constant DECLINED. Handlers should return this if they are not going to handle the request.
apache2.DONE
internal constant DONE.
apache2.version
Apache HTTP server version string
apache2.HTTP_MOVED_TEMPORARILY
HTTP status code
apache2.PROXYREQ_NONE, apache2.PROXYREQ_PROXY, apache2.PROXYREQ_REVERSE, apache2.PROXYREQ_RESPONSE
internal constants used by mod_proxy
apache2.AUTHZ_DENIED, apache2.AUTHZ_GRANTED, apache2.AUTHZ_NEUTRAL, apache2.AUTHZ_GENERAL_ERROR, apache2.AUTHZ_DENIED_NO_USER
internal constants used by mod_authz_core

(Other HTTP status codes are not yet implemented.)

LuaRoot Specify the base path for resolving relative paths for mod_lua directives LuaRoot /path/to/a/directory server configvirtual host directory.htaccess All

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.

LuaScope One of once, request, conn, thread -- default is once LuaScope once|request|conn|thread|server [min] [max] LuaScope once server configvirtual host directory.htaccess All

Specify the lifecycle scope of the Lua interpreter which will be used by handlers in this "Directory." The default is "once"

once:
use the interpreter once and throw it away.
request:
use the interpreter to handle anything based on the same file within this request, which is also request scoped.
conn:
Same as request but attached to the connection_rec
thread:
Use the interpreter for the lifetime of the thread handling the request (only available with threaded MPMs).
server:
This one is different than others because the server scope is quite long lived, and multiple threads will have the same server_rec. To accommodate this, server scoped Lua states are stored in an apr resource list. The 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.

LuaMapHandler Map a path to a lua handler LuaMapHandler uri-pattern /path/to/lua/script.lua [function-name] server configvirtual host directory.htaccess All

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.

Examples: LuaMapHandler /(\w+)/(\w+) /scripts/$1.lua handle_$2

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.

LuaMapHandler /bingo /scripts/wombat.lua

This would invoke the "handle" function, which is the default if no specific function name is provided.

LuaPackagePath Add a directory to lua's package.path LuaPackagePath /path/to/include/?.lua server configvirtual host directory.htaccess All

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.

Examples: LuaPackagePath /scripts/lib/?.lua LuaPackagePath /scripts/lib/?/init.lua
LuaPackageCPath Add a directory to lua's package.cpath LuaPackageCPath /path/to/include/?.soa server configvirtual host directory.htaccess All

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.

LuaCodeCache Configure the compiled code cache. LuaCodeCache stat|forever|never LuaCodeCache stat server configvirtual host directory.htaccess All

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.

Examples: LuaCodeCache stat LuaCodeCache forever LuaCodeCache never
LuaHookTranslateName Provide a hook for the translate name phase of request processing LuaHookTranslateName /path/to/lua/script.lua hook_function_name [early|late] server configvirtual host All The optional third argument is supported in 2.3.15 and later

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:

# httpd.conf LuaHookTranslateName /scripts/conf/hooks.lua silly_mapper -- /scripts/conf/hooks.lua -- require "apache2" function silly_mapper(r) if r.uri == "/" then r.filename = "/var/www/home.lua" return apache2.OK else return apache2.DECLINED end end Context

This directive is not valid in Directory, Files, or htaccess context.

Ordering

The optional arguments "early" or "late" control when this script runs relative to other modules.

LuaHookFixups Provide a hook for the fixups phase of a request processing LuaHookFixups /path/to/lua/script.lua hook_function_name server configvirtual host directory.htaccess All

Just like LuaHookTranslateName, but executed at the fixups phase

LuaHookMapToStorage Provide a hook for the map_to_storage phase of request processing LuaHookMapToStorage /path/to/lua/script.lua hook_function_name server configvirtual host directory.htaccess All

Like LuaHookTranslateName but executed at the map-to-storage phase of a request. Modules like mod_cache run at this phase, which makes for an interesting example on what to do here:

LuaHookMapToStorage /path/to/lua/script.lua check_cache require"apache2" cached_files = {} function read_file(filename) local input = io.open(filename, "r") if input then local data = input:read("*a") cached_files[filename] = data file = cached_files[filename] input:close() end return cached_files[filename] end function check_cache(r) if r.filename:match("%.png$") then -- Only match PNG files local file = cached_files[r.filename] -- Check cache entries if not file then file = read_file(r.filename) -- Read file into cache end if file then -- If file exists, write it out r.status = 200 r:write(file) r:info(("Sent %s to client from cache"):format(r.filename)) return apache2.DONE -- skip default handler for PNG files end end return apache2.DECLINED -- If we had nothing to do, let others serve this. end
LuaHookCheckUserID Provide a hook for the check_user_id phase of request processing LuaHookCheckUserID /path/to/lua/script.lua hook_function_name [early|late] server configvirtual host directory.htaccess All The optional third argument is supported in 2.3.15 and later

...

Ordering

The optional arguments "early" or "late" control when this script runs relative to other modules.

LuaHookTypeChecker Provide a hook for the type_checker phase of request processing LuaHookTypeChecker /path/to/lua/script.lua hook_function_name server configvirtual host directory.htaccess All

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:

LuaHookTypeChecker /path/to/lua/script.lua type_checker function type_checker(r) if r.uri:match("%.to_gif$") then -- match foo.png.to_gif r.content_type = "image/gif" -- assign it the image/gif type r.handler = "gifWizard" -- tell the gifWizard module to handle this r.filename = r.uri:gsub("%.to_gif$", "") -- fix the filename requested return apache2.OK end return apache2.DECLINED end
LuaHookAuthChecker Provide a hook for the auth_checker phase of request processing LuaHookAuthChecker /path/to/lua/script.lua hook_function_name [early|late] server configvirtual host directory.htaccess All The optional third argument is supported in 2.3.15 and later

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:

require 'apache2' -- fake authcheck hook -- If request has no auth info, set the response header and -- return a 401 to ask the browser for basic auth info. -- If request has auth info, don't actually look at it, just -- pretend we got userid 'foo' and validated it. -- Then check if the userid is 'foo' and accept the request. function authcheck_hook(r) -- look for auth info auth = r.headers_in['Authorization'] if auth ~= nil then -- fake the user r.user = 'foo' end if r.user == nil then r:debug("authcheck: user is nil, returning 401") r.err_headers_out['WWW-Authenticate'] = 'Basic realm="WallyWorld"' return 401 elseif r.user == "foo" then r:debug('user foo: OK') else r:debug("authcheck: user='" .. r.user .. "'") r.err_headers_out['WWW-Authenticate'] = 'Basic realm="WallyWorld"' return 401 end return apache2.OK end Ordering

The optional arguments "early" or "late" control when this script runs relative to other modules.

LuaHookAccessChecker Provide a hook for the access_checker phase of request processing LuaHookAccessChecker /path/to/lua/script.lua hook_function_name [early|late] server configvirtual host directory.htaccess All The optional third argument is supported in 2.3.15 and later

Add your hook to the access_checker phase. An access checker hook function usually returns OK, DECLINED, or HTTP_FORBIDDEN.

Ordering

The optional arguments "early" or "late" control when this script runs relative to other modules.

LuaHookInsertFilter Provide a hook for the insert_filter phase of request processing LuaHookInsertFilter /path/to/lua/script.lua hook_function_name server configvirtual host directory.htaccess All

Not Yet Implemented

LuaInherit Controls how parent configuration sections are merged into children LuaInherit none|parent-first|parent-last LuaInherit parent-first server configvirtual host directory.htaccess All 2.4.0 and later

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.

LuaQuickHandler Provide a hook for the quick handler of request processing LuaQuickHandler /path/to/script.lua hook_function_name server configvirtual host All

...

Context

This directive is not valid in Directory, Files, or htaccess context.

LuaAuthzProvider Plug an authorization provider function into mod_authz_core LuaAuthzProvider provider_name /path/to/lua/script.lua function_name server config 2.5.0 and later

After a lua function has been registered as authorization provider, it can be used with the Require directive:

LuaRoot /usr/local/apache2/lua LuaAuthzProvider foo authz.lua authz_check_foo <Location /> Require foo johndoe </Location> require "apache2" function authz_check_foo(r, who) if r.user ~= who then return apache2.AUTHZ_DENIED return apache2.AUTHZ_GRANTED end