Apache HTTP Server Version 2.4

Apache > HTTP Server > Documentation > Version 2.4 > Modules

# Apache Module mod_lua

Available Languages: en | fr

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

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.

### Directives

### Topics

- Basic Configuration
- Writing Handlers
- Writing Authorization Providers
- Writing Hooks
- Data Structures
- Logging Functions
- apache2 Package
- Database connectivity

- Comments

## 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.

## 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 purpose, such as mapping requests to the filesystem, performing access control, or setting mimetypes. General purpose hooks that simply run at handy times in the request lifecycle exist as well.

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: It is currently undefined as to whether this runs 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 (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 | yes
  `assbackwards` | boolean | no
  `canonical_filename` | string | no
  `content_encoding` | string | no
  `content_type` | string | yes
  `context_prefix` | string | no
  `context_document_root` | string | no
  `document_root` | string | no
  `err_headers_out` | table | no
  `filename` | string | yes
  `handler` | string | yes
  `headers_in` | table | yes
  `headers_out` | table | yes
  `hostname` | string | no
  `log_id` | string | no
  `method` | string | no
  `notes` | table | yes
  `path_info` | string | no
  `protocol` | string | no
  `proxyreq` | string | yes
  `range` | string | no
  `subprocess_env` | table | yes
  `status` | number | yes
  `the_request` | string | no
  `unparsed_uri` | string | no
  `uri` | string | yes
  `user` | string | yes
  `useragent_ip` | string | no

  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([sizeLimit]) -- parse the request body as a POST and return  a lua table.
                               -- An optional number may be passed to specify the maximum number
                               -- of bytes to parse. Default is 8192 bytes.

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

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

      r:dbacquire(dbType[, dbParams]) -- Acquires a connection to a database and returns a database class.
                                      -- See 'Database connectivity' for details.

## 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 a notice log message")

            r:warn("This is a warn log message")

            r:err("This is an err log message")

            r:alert("This is an alert log message")

            r:crit("This is a 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`

(Other HTTP status codes are not yet implemented.)

## Database connectivity

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.

Connecting and firing off queries is as easy as:

    function handler(r)
        local database, err = r:dbacquire("mysql", "server=localhost&user=root&database=mydb")
        if not err then
            local results, err = database:select(r, "SELECT `name`, `age` FROM `people` WHERE 1")
            if not err then
                local rows = results(0) -- fetch all rows synchronously
                for k, row in pairs(rows) do
                    r:puts( string.format("Name: %s, Age: %s<br/>", row[1], row[2]) )
                end
            else
                r:puts("Database query error: " .. err)
            end
            database:close()
        else
            r:puts("Could not connect to the database: " .. err)
        end
    end

To utilize `mod_dbd`, simply specify `mod_dbd` as the database type, or leave the field blank:

        local database = r:dbacquire("mod_dbd")

### Database object and contained functions

The database object returned by `dbacquire` has the following methods:

Normal select and query from a database:

    -- Run a statement and return the number of rows affected:
    local affected, errmsg = database:query(r, "DELETE FROM `tbl` WHERE 1")

    -- Run a statement and return a result set that can be used synchronously or async:
    local result, errmsg = database:select(r, "SELECT * FROM `people` WHERE 1")

Using prepared statements (recommended):

    -- Create and run a prepared statement:
    local statement, errmsg = database:prepare(r, "DELETE FROM `tbl` WHERE `age` > %u")
    if not errmsg then
        local result, errmsg = statement:query(20) -- run the statement with age >20
    end

    -- Fetch a prepared statement from a DBDPrepareSQL directive:
    local statement, errmsg = database:prepared(r, "someTag")
    if not errmsg then
        local result, errmsg = statement:select("John Doe", 123) -- inject the values "John Doe" and 123 into the statement
    end

Escaping values, closing databases etc:

    -- Escape a value for use in a statement:
    local escaped = database:escape(r, [["'|blabla]])

    -- Close a database connection and free up handles:
    database:close()

    -- Check whether a database connection is up and running:
    local connected = database:active()

### Working with result sets

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:

    -- fetch a result set using a regular query:
    local result, err = db:select(r, "SELECT * FROM `tbl` WHERE 1")

    local rows = result(0) -- Fetch ALL rows synchronously
    local row = result(-1) -- Fetch the next available row, asynchronously
    local row = result(1234) -- Fetch row number 1234, 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:

    function rows(resultset, async)
        local a = 0
        local function getnext()
            a = a + 1
            local row = resultset(-1)
            return row and a or nil, row
        end
        if not async then
            return pairs(resultset(0))
        else
            return getnext, self
        end
    end

    local statement, err = db:prepare(r, "SELECT * FROM `tbl` WHERE `age` > %u")
    if not err then
         -- fetch rows asynchronously:
        local result, err = statement:select(20)
        if not err then
            for index, row in rows(result, true) do
                ....
            end
        end

         -- fetch rows synchronously:
        local result, err = statement:select(20)
        if not err then
            for index, row in rows(result, false) do
                ....
            end
        end
    end

### Closing a database connection

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:

    -- Method 1: Manually close a handle
    local database = r:dbacquire("mod_dbd")
    database:close() -- All done

    -- Method 2: Letting the garbage collector close it
    local database = r:dbacquire("mod_dbd")
    database = nil -- throw away the reference
    collectgarbage() -- close the handle via GC

### Precautions when working with databases

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`.

## LuaAuthzProvider Directive

Description: | Plug an authorization provider function into `mod_authz_core`
Syntax: | `LuaAuthzProvider provider_name /path/to/lua/script.lua function_name`
Context: | server config
Status: | Experimental
Module: | mod_lua
Compatibility: | 2.4.3 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 bar
    </Location>

## LuaHookAccessChecker Directive

Description: | Provide a hook for the access_checker phase of request processing
Syntax: | `LuaHookAccessChecker /path/to/lua/script.lua hook_function_name [early|late]`
Context: | server config, virtual host, directory, .htaccess
Override: | All
Status: | Experimental
Module: | mod_lua
Compatibility: | 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.

## LuaHookAuthChecker Directive

Description: | Provide a hook for the auth_checker phase of request processing
Syntax: | `LuaHookAuthChecker /path/to/lua/script.lua hook_function_name [early|late]`
Context: | server config, virtual host, directory, .htaccess
Override: | All
Status: | Experimental
Module: | mod_lua
Compatibility: | 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.

## 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 [early|late]`
Context: | server config, virtual host, directory, .htaccess
Override: | All
Status: | Experimental
Module: | mod_lua
Compatibility: | 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.

## 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

## 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

## 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

...

## LuaHookTranslateName Directive

Description: | Provide a hook for the translate name phase of request processing
Syntax: | `LuaHookTranslateName /path/to/lua/script.lua hook_function_name [early|late]`
Context: | server config, virtual host
Override: | All
Status: | Experimental
Module: | mod_lua
Compatibility: | 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.

## 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

...

## LuaInherit Directive

Description: | Controls how parent configuration sections are merged into children
Syntax: | `LuaInherit none|parent-first|parent-last`
Default: | `LuaInherit parent-first`
Context: | server config, virtual host, directory, .htaccess
Override: | All
Status: | Experimental
Module: | mod_lua
Compatibility: | 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.

## 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.

## 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

## LuaQuickHandler Directive

Description: | Provide a hook for the quick handler of request processing
Syntax: | `LuaQuickHandler /path/to/script.lua hook_function_name`
Context: | server config, virtual host
Override: | All
Status: | Experimental
Module: | mod_lua

...

### Context

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

## 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.

## LuaScope Directive

Description: | One of once, request, conn, thread -- default is once
Syntax: | `LuaScope once|request|conn|thread`
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
thread:
  Use the interpreter for the lifetime of the thread handling the request (only available with threaded MPMs).

Available Languages: en | fr

## Comments

Notice:
This is not a Q&A section. Comments placed here should be pointed towards suggestions on improving the documentation or server, and may be removed again by our moderators if they are either implemented or considered invalid/off-topic. Questions on how to manage the Apache HTTP Server should be directed at either our IRC channel, #httpd, on Freenode, or sent to our mailing lists.