<-
Apache > HTTP Server > Documentation > Version 2.3 > Modules

Apache Module mod_lua

Available Languages:  en 

Description:Provides Lua hooks into various portions of the httpd request processing
Status:Experimental
Module Identifier:lua_module
Source File:mod_lua.c
Compatibility:2.3 and later

Summary

Someone needs to write this. Include a link to the Lua website.

Directives

Topics

top

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.

top

Writing Handlers

mod_lua always looks to invoke a 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"

function handle_something(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", k, v) )
        end
    elseif r.method == 'POST' then
        for k, v in pairs( r:parsebody() ) do
            r:puts( string.format("%s: %s", k, v) )
        end
    else
        r:puts("unknown 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.

top

Writing Hooks

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

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
top

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 (see httpd.h until we get better docs here) 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
ap_auth_type string no
args string no
assbackwards boolean no
canonical_filename string no
content_encoding string no
content_type string yes
document_root string no
err_headers_out table no
filename string yes
headers_in table yes
headers_out table yes
hostname string no
method string no
notes table yes
path_info string no
protocol string no
range string no
status number yes
the_request string no
unparsed_uri string no
uri string yes
user string yes

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 the request body as a POST and return a lua table

r:puts("hello", " world", "!") -- print to response body

r:write("a single string") -- print to response body

top

Logging Functions

-- examples of logging messages
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")

top

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

(Other HTTP status codes are not yet implemented.)

top

LuaCodeCache Directive

Description:Configure the compiled code cache.
Syntax:LuaCodeCache stat|forever|never
Default:LuaCodeCache stat
Context:server config, virtual host, directory, .htaccess
Override:All
Status:Experimental
Module:mod_lua

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

top

LuaHookAccessChecker Directive

Description:Provide a hook for the access_checker phase of request processing
Syntax:LuaHookAccessChecker /path/to/lua/script.lua hook_function_name
Context:server config, virtual host, directory, .htaccess
Override:All
Status:Experimental
Module:mod_lua

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

top

LuaHookAuthChecker Directive

Description:Provide a hook for the auth_checker phase of request processing
Syntax:LuaHookAuthChecker /path/to/lua/script.lua hook_function_name
Context:server config, virtual host, directory, .htaccess
Override:All
Status:Experimental
Module:mod_lua

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
top

LuaHookCheckUserID Directive

Description:Provide a hook for the check_user_id phase of request processing
Syntax:LuaHookCheckUserID /path/to/lua/script.lua hook_function_name
Context:server config, virtual host, directory, .htaccess
Override:All
Status:Experimental
Module:mod_lua

...

top

LuaHookFixups Directive

Description:Provide a hook for the fixups phase of request processing
Syntax:LuaHookFixups /path/to/lua/script.lua hook_function_name
Context:server config, virtual host, directory, .htaccess
Override:All
Status:Experimental
Module:mod_lua

Just like LuaHookTranslateName, but executed at the fixups phase

top

LuaHookInsertFilter Directive

Description:Provide a hook for the insert_filter phase of request processing
Syntax:LuaHookInsertFilter /path/to/lua/script.lua hook_function_name
Context:server config, virtual host, directory, .htaccess
Override:All
Status:Experimental
Module:mod_lua

Not Yet Implemented

top

LuaHookMapToStorage Directive

Description:Provide a hook for the map_to_storage phase of request processing
Syntax:LuaHookMapToStorage /path/to/lua/script.lua hook_function_name
Context:server config, virtual host, directory, .htaccess
Override:All
Status:Experimental
Module:mod_lua

...

top

LuaHookTranslateName Directive

Description:Provide a hook for the translate name phase of request processing
Syntax:LuaHookTranslateName /path/to/lua/script.lua hook_function_name
Context:server config, virtual host, directory, .htaccess
Override:All
Status:Experimental
Module:mod_lua

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.file = "/var/www/home.lua"
        return apache2.OK
    else
        return apache2.DECLINED
    end
end
top

LuaHookTypeChecker Directive

Description:Provide a hook for the type_checker phase of request processing
Syntax:LuaHookTypeChecker /path/to/lua/script.lua hook_function_name
Context:server config, virtual host, directory, .htaccess
Override:All
Status:Experimental
Module:mod_lua

...

top

LuaMapHandler Directive

Description:Map a path to a lua handler
Syntax:LuaMapHandler uri-pattern /path/to/lua/script.lua [function-name]
Context:server config, virtual host, directory, .htaccess
Override:All
Status:Experimental
Module:mod_lua

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.

top

LuaPackageCPath Directive

Description:Add a directory to lua's package.cpath
Syntax:LuaPackageCPath /path/to/include/?.soa
Context:server config, virtual host, directory, .htaccess
Override:All
Status:Experimental
Module:mod_lua

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.

top

LuaPackagePath Directive

Description:Add a directory to lua's package.path
Syntax:LuaPackagePath /path/to/include/?.lua
Context:server config, virtual host, directory, .htaccess
Override:All
Status:Experimental
Module:mod_lua

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

top

LuaQuickHandler Directive

Description:Provide a hook for the quick handler of request processing
Syntax:
Context:server config, virtual host, directory, .htaccess
Override:All
Status:Experimental
Module:mod_lua

...

top

LuaRoot Directive

Description:Specify the base path for resolving relative paths for mod_lua directives
Syntax:LuaRoot /path/to/a/directory
Context:server config, virtual host, directory, .htaccess
Override:All
Status:Experimental
Module:mod_lua

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.

top

LuaScope Directive

Description:One of once, request, conn, server -- default is once
Syntax:LuaScope once|request|conn|server [max|min max]
Default:LuaScope once
Context:server config, virtual host, directory, .htaccess
Override:All
Status:Experimental
Module:mod_lua

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
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 interpreter are stored in an apr resource list. The min and max arguments are intended to specify the pool size, but are unused at this time.

Available Languages:  en