2 <!DOCTYPE modulesynopsis SYSTEM "../style/modulesynopsis.dtd">
3 <?xml-stylesheet type="text/xsl" href="../style/manual.en.xsl"?>
4 <!-- $LastChangedRevision$ -->
7 Licensed to the Apache Software Foundation (ASF) under one or more
8 contributor license agreements. See the NOTICE file distributed with
9 this work for additional information regarding copyright ownership.
10 The ASF licenses this file to You under the Apache License, Version 2.0
11 (the "License"); you may not use this file except in compliance with
12 the License. You may obtain a copy of the License at
14 http://www.apache.org/licenses/LICENSE-2.0
16 Unless required by applicable law or agreed to in writing, software
17 distributed under the License is distributed on an "AS IS" BASIS,
18 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 See the License for the specific language governing permissions and
20 limitations under the License.
23 <modulesynopsis metafile="mod_lua.xml.meta">
27 <description>Provides Lua hooks into various portions of the httpd
28 request processing</description>
29 <status>Experimental</status>
30 <sourcefile>mod_lua.c</sourcefile>
31 <identifier>lua_module</identifier>
32 <compatibility>2.3 and later</compatibility>
35 <p>This module allows the server to be extended with scripts written in the
36 Lua programming language. The extension points (hooks) available with
37 <module>mod_lua</module> include many of the hooks available to
38 natively compiled Apache HTTP Server modules, such as mapping requests to
39 files, generating dynamic responses, access control, authentication, and
42 <p>More information on the Lua programming language can be found at the
43 <a href="http://www.lua.org/">the Lua website</a>.</p>
45 <note><code>mod_lua</code> is still in experimental state.
46 Until it is declared stable, usage and behavior may change
47 at any time, even between stable releases of the 2.4.x series.
48 Be sure to check the CHANGES file before upgrading.</note>
50 <note type="warning"><title>Warning</title>
51 <p>This module holds a great deal of power over httpd, which is both a
52 strength and a potential security risk. It is <strong>not</strong> recommended
53 that you use this module on a server that is shared with users you do not
54 trust, as it can be abused to change the internal workings of httpd.</p>
59 <section id="basicconf"><title>Basic Configuration</title>
61 <p>The basic module loading directive is</p>
63 <highlight language="config">
64 LoadModule lua_module modules/mod_lua.so
68 <code>mod_lua</code> provides a handler named <code>lua-script</code>,
69 which can be used with a <directive
70 module="core">SetHandler</directive> or
71 <directive module="mod_mime">AddHandler</directive> directive:</p>
73 <highlight language="config">
80 This will cause <code>mod_lua</code> to handle requests for files
81 ending in <code>.lua</code> by invoking that file's
82 <code>handle</code> function.
85 <p>For more flexibility, see <directive>LuaMapHandler</directive>.
90 <section id="writinghandlers"><title>Writing Handlers</title>
91 <p> In the Apache HTTP Server API, the handler is a specific kind of hook
92 responsible for generating the response. Examples of modules that include a
93 handler are <module>mod_proxy</module>, <module>mod_cgi</module>,
94 and <module>mod_status</module>.</p>
96 <p><code>mod_lua</code> always looks to invoke a Lua function for the handler, rather than
97 just evaluating a script body CGI style. A handler function looks
98 something like this:</p>
101 <highlight language="lua">
102 <strong>example.lua</strong><br/>
108 This is the default method name for Lua handlers, see the optional
109 function-name in the LuaMapHandler directive to choose a different
113 r.content_type = "text/plain"
115 if r.method == 'GET' then
116 r:puts("Hello Lua World!\n")
117 for k, v in pairs( r:parseargs() ) do
118 r:puts( string.format("%s: %s\n", k, v) )
120 elseif r.method == 'POST' then
121 r:puts("Hello Lua World!\n")
122 for k, v in pairs( r:parsebody() ) do
123 r:puts( string.format("%s: %s\n", k, v) )
125 elseif r.method == 'PUT' then
126 -- use our own Error contents
127 r:puts("Unsupported HTTP method " .. r.method)
131 -- use the ErrorDocument
139 This handler function just prints out the uri or form encoded
140 arguments to a plaintext page.
144 This means (and in fact encourages) that you can have multiple
145 handlers (or hooks, or filters) in the same script.
150 <section id="writingauthzproviders">
151 <title>Writing Authorization Providers</title>
153 <p><module>mod_authz_core</module> provides a high-level interface to
154 authorization that is much easier to use than using into the relevant
155 hooks directly. The first argument to the
156 <directive module="mod_authz_core">Require</directive> directive gives
157 the name of the responsible authorization provider. For any
158 <directive module="mod_authz_core">Require</directive> line,
159 <module>mod_authz_core</module> will call the authorization provider
160 of the given name, passing the rest of the line as parameters. The
161 provider will then check authorization and pass the result as return
164 <p>The authz provider is normally called before authentication. If it needs to
165 know the authenticated user name (or if the user will be authenticated at
166 all), the provider must return <code>apache2.AUTHZ_DENIED_NO_USER</code>.
167 This will cause authentication to proceed and the authz provider to be
168 called a second time.</p>
170 <p>The following authz provider function takes two arguments, one ip
171 address and one user name. It will allow access from the given ip address
172 without authentication, or if the authenticated user matches the second
175 <highlight language="lua">
176 <strong>authz_provider.lua</strong><br/>
180 function authz_check_foo(r, ip, user)
181 if r.useragent_ip == ip then
182 return apache2.AUTHZ_GRANTED
183 elseif r.user == nil then
184 return apache2.AUTHZ_DENIED_NO_USER
185 elseif r.user == user then
186 return apache2.AUTHZ_GRANTED
188 return apache2.AUTHZ_DENIED
193 <p>The following configuration registers this function as provider
194 <code>foo</code> and configures it for URL <code>/</code>:</p>
195 <highlight language="config">
196 LuaAuthzProvider foo authz_provider.lua authz_check_foo
198 Require foo 10.1.2.3 john_doe
204 <section id="writinghooks"><title>Writing Hooks</title>
206 <p>Hook functions are how modules (and Lua scripts) participate in the
207 processing of requests. Each type of hook exposed by the server exists for
208 a specific purpose, such as mapping requests to the file system,
209 performing access control, or setting mime types:</p>
211 <table border="1" style="zebra">
214 <th>mod_lua directive</th>
218 <td>Quick handler</td>
219 <td><directive module="mod_lua">LuaQuickHandler</directive></td>
220 <td>This is the first hook that will be called after a request has
221 been mapped to a host or virtual host</td>
224 <td>Translate name</td>
225 <td><directive module="mod_lua">LuaHookTranslateName</directive></td>
226 <td>This phase translates the requested URI into a filename on the
227 system. Modules such as <module>mod_alias</module> and
228 <module>mod_rewrite</module> operate in this phase.</td>
231 <td>Map to storage</td>
232 <td><directive module="mod_lua">LuaHookMapToStorage</directive></td>
233 <td>This phase maps files to their physical, cached or external/proxied storage.
234 It can be used by proxy or caching modules</td>
237 <td>Check Access</td>
238 <td><directive module="mod_lua">LuaHookAccessChecker</directive></td>
239 <td>This phase checks whether a client has access to a resource. This
240 phase is run before the user is authenticated, so beware.
244 <td>Check User ID</td>
245 <td><directive module="mod_lua">LuaHookCheckUserID</directive></td>
246 <td>This phase it used to check the negotiated user ID</td>
249 <td>Check Authorization</td>
250 <td><directive module="mod_lua">LuaHookAuthChecker</directive> or
251 <directive module="mod_lua">LuaAuthzProvider</directive></td>
252 <td>This phase authorizes a user based on the negotiated credentials, such as
253 user ID, client certificate etc.
258 <td><directive module="mod_lua">LuaHookTypeChecker</directive></td>
259 <td>This phase checks the requested file and assigns a content type and
264 <td><directive module="mod_lua">LuaHookFixups</directive></td>
265 <td>This is the final "fix anything" phase before the content handlers
266 are run. Any last-minute changes to the request should be made here.</td>
269 <td>Content handler</td>
270 <td>fx. <code>.lua</code> files or through <directive module="mod_lua">LuaMapHandler</directive></td>
271 <td>This is where the content is handled. Files are read, parsed, some are run,
272 and the result is sent to the client</td>
276 <td><directive module="mod_lua">LuaHookLog</directive></td>
277 <td>Once a request has been handled, it enters several logging phases,
278 which logs the request in either the error or access log. Mod_lua
279 is able to hook into the start of this and control logging output.</td>
284 <p>Hook functions are passed the request object as their only argument
285 (except for LuaAuthzProvider, which also gets passed the arguments from
286 the Require directive).
287 They can return any value, depending on the hook, but most commonly
288 they'll return OK, DONE, or DECLINED, which you can write in Lua as
289 <code>apache2.OK</code>, <code>apache2.DONE</code>, or
290 <code>apache2.DECLINED</code>, or else an HTTP status code.</p>
293 <highlight language="lua">
294 <strong>translate_name.lua</strong><br/>
295 -- example hook that rewrites the URI to a filesystem path.
299 function translate_name(r)
300 if r.uri == "/translate-name" then
301 r.filename = r.document_root .. "/find_me.txt"
304 -- we don't care about this URL, give another module a chance
305 return apache2.DECLINED
310 <highlight language="lua">
311 <strong>translate_name2.lua</strong><br/>
312 --[[ example hook that rewrites one URI to another URI. It returns a
313 apache2.DECLINED to give other URL mappers a chance to work on the
314 substitution, including the core translate_name hook which maps based
317 Note: Use the early/late flags in the directive to make it run before
323 function translate_name(r)
324 if r.uri == "/translate-name" then
325 r.uri = "/find_me.txt"
326 return apache2.DECLINED
328 return apache2.DECLINED
333 <section id="datastructures"><title>Data Structures</title>
338 <p>The request_rec is mapped in as a userdata. It has a metatable
339 which lets you do useful things with it. For the most part it
340 has the same fields as the request_rec struct, many of which are writable as
341 well as readable. (The table fields' content can be changed, but the
342 fields themselves cannot be set to different tables.)</p>
344 <table border="1" style="zebra">
347 <th><strong>Name</strong></th>
348 <th><strong>Lua type</strong></th>
349 <th><strong>Writable</strong></th>
350 <th><strong>Description</strong></th>
353 <td><code>allowoverrides</code></td>
356 <td>The AllowOverride options applied to the current request.</td>
359 <td><code>ap_auth_type</code></td>
362 <td>If an authentication check was made, this is set to the type
363 of authentication (f.x. <code>basic</code>)</td>
366 <td><code>args</code></td>
369 <td>The query string arguments extracted from the request
370 (f.x. <code>foo=bar&name=johnsmith</code>)</td>
373 <td><code>assbackwards</code></td>
376 <td>Set to true if this is an HTTP/0.9 style request
377 (e.g. <code>GET /foo</code> (with no headers) )</td>
380 <td><code>auth_name</code></td>
383 <td>The realm name used for authorization (if applicable).</td>
386 <td><code>banner</code></td>
389 <td>The server banner, f.x. <code>Apache HTTP Server/2.4.3 openssl/0.9.8c</code></td>
392 <td><code>basic_auth_pw</code></td>
395 <td>The basic auth password sent with this request, if any</td>
398 <td><code>canonical_filename</code></td>
401 <td>The canonical filename of the request</td>
404 <td><code>content_encoding</code></td>
407 <td>The content encoding of the current request</td>
410 <td><code>content_type</code></td>
413 <td>The content type of the current request, as determined in the
414 type_check phase (f.x. <code>image/gif</code> or <code>text/html</code>)</td>
417 <td><code>context_prefix</code></td>
423 <td><code>context_document_root</code></td>
430 <td><code>document_root</code></td>
433 <td>The document root of the host</td>
436 <td><code>err_headers_out</code></td>
439 <td>MIME header environment for the response, printed even on errors and
440 persist across internal redirects</td>
443 <td><code>filename</code></td>
446 <td>The file name that the request maps to, f.x. /www/example.com/foo.txt. This can be
447 changed in the translate-name or map-to-storage phases of a request to allow the
448 default handler (or script handlers) to serve a different file than what was requested.</td>
451 <td><code>handler</code></td>
454 <td>The name of the <a href="../handler.html">handler</a> that should serve this request, f.x.
455 <code>lua-script</code> if it is to be served by mod_lua. This is typically set by the
456 <directive module="mod_mime">AddHandler</directive> or <directive module="core">SetHandler</directive>
457 directives, but could also be set via mod_lua to allow another handler to serve up a specific request
458 that would otherwise not be served by it.
463 <td><code>headers_in</code></td>
466 <td>MIME header environment from the request. This contains headers such as <code>Host,
467 User-Agent, Referer</code> and so on.</td>
470 <td><code>headers_out</code></td>
473 <td>MIME header environment for the response.</td>
476 <td><code>hostname</code></td>
479 <td>The host name, as set by the <code>Host:</code> header or by a full URI.</td>
482 <td><code>is_https</code></td>
485 <td>Whether or not this request is done via HTTPS</td>
488 <td><code>is_initial_req</code></td>
491 <td>Whether this request is the initial request or a sub-request</td>
494 <td><code>limit_req_body</code></td>
497 <td>The size limit of the request body for this request, or 0 if no limit.</td>
500 <td><code>log_id</code></td>
503 <td>The ID to identify request in access and error log.</td>
506 <td><code>method</code></td>
509 <td>The request method, f.x. <code>GET</code> or <code>POST</code>.</td>
512 <td><code>notes</code></td>
515 <td>A list of notes that can be passed on from one module to another.</td>
518 <td><code>options</code></td>
521 <td>The Options directive applied to the current request.</td>
524 <td><code>path_info</code></td>
527 <td>The PATH_INFO extracted from this request.</td>
530 <td><code>port</code></td>
533 <td>The server port used by the request.</td>
536 <td><code>protocol</code></td>
539 <td>The protocol used, f.x. <code>HTTP/1.1</code></td>
542 <td><code>proxyreq</code></td>
545 <td>Denotes whether this is a proxy request or not. This value is generally set in
546 the post_read_request/translate_name phase of a request.</td>
549 <td><code>range</code></td>
552 <td>The contents of the <code>Range:</code> header.</td>
555 <td><code>remaining</code></td>
558 <td>The number of bytes remaining to be read from the request body.</td>
561 <td><code>server_built</code></td>
564 <td>The time the server executable was built.</td>
567 <td><code>server_name</code></td>
570 <td>The server name for this request.</td>
573 <td><code>some_auth_required</code></td>
576 <td>Whether some authorization is/was required for this request.</td>
579 <td><code>subprocess_env</code></td>
582 <td>The environment variables set for this request.</td>
585 <td><code>started</code></td>
588 <td>The time the server was (re)started, in seconds since the epoch (Jan 1st, 1970)</td>
591 <td><code>status</code></td>
594 <td>The (current) HTTP return code for this request, f.x. <code>200</code> or <code>404</code>.</td>
597 <td><code>the_request</code></td>
600 <td>The request string as sent by the client, f.x. <code>GET /foo/bar HTTP/1.1</code>.</td>
603 <td><code>unparsed_uri</code></td>
606 <td>The unparsed URI of the request</td>
609 <td><code>uri</code></td>
612 <td>The URI after it has been parsed by httpd</td>
615 <td><code>user</code></td>
618 <td>If an authentication check has been made, this is set to the name of the authenticated user.</td>
621 <td><code>useragent_ip</code></td>
624 <td>The IP of the user agent making the request</td>
630 <section id="functions"><title>Built in functions</title>
632 <p>The request_rec object has (at least) the following methods:</p>
634 <highlight language="lua">
635 r:flush() -- flushes the output buffer.
636 -- Returns true if the flush was successful, false otherwise.
638 while we_have_stuff_to_send do
639 r:puts("Bla bla bla\n") -- print something to client
640 r:flush() -- flush the buffer (send to client)
641 r.usleep(500000) -- fake processing time for 0.5 sec. and repeat
645 <highlight language="lua">
646 r:addoutputfilter(name|function) -- add an output filter:
648 r:addoutputfilter("fooFilter") -- add the fooFilter to the output stream
651 <highlight language="lua">
652 r:sendfile(filename) -- sends an entire file to the client, using sendfile if supported by the current platform:
654 if use_sendfile_thing then
655 r:sendfile("/var/www/large_file.img")
659 <highlight language="lua">
660 r:parseargs() -- returns two tables; one standard key/value table for regular GET data,
661 -- and one for multi-value data (fx. foo=1&foo=2&foo=3):
663 local GET, GETMULTI = r:parseargs()
664 r:puts("Your name is: " .. GET['name'] or "Unknown")
667 <highlight language="lua">
668 r:parsebody([sizeLimit]) -- parse the request body as a POST and return two lua tables,
669 -- just like r:parseargs().
670 -- An optional number may be passed to specify the maximum number
671 -- of bytes to parse. Default is 8192 bytes:
673 local POST, POSTMULTI = r:parsebody(1024*1024)
674 r:puts("Your name is: " .. POST['name'] or "Unknown")
677 <highlight language="lua">
678 r:puts("hello", " world", "!") -- print to response body, self explanatory
681 <highlight language="lua">
682 r:write("a single string") -- print to response body, self explanatory
685 <highlight language="lua">
686 r:escape_html("<html>test</html>") -- Escapes HTML code and returns the escaped result
689 <highlight language="lua">
690 r:base64_encode(string) -- Encodes a string using the Base64 encoding standard:
692 local encoded = r:base64_encode("This is a test") -- returns VGhpcyBpcyBhIHRlc3Q=
695 <highlight language="lua">
696 r:base64_decode(string) -- Decodes a Base64-encoded string:
698 local decoded = r:base64_decode("VGhpcyBpcyBhIHRlc3Q=") -- returns 'This is a test'
701 <highlight language="lua">
702 r:md5(string) -- Calculates and returns the MD5 digest of a string (binary safe):
704 local hash = r:md5("This is a test") -- returns ce114e4501d2f4e2dcea3e17b546f339
707 <highlight language="lua">
708 r:sha1(string) -- Calculates and returns the SHA1 digest of a string (binary safe):
710 local hash = r:sha1("This is a test") -- returns a54d88e06612d820bc3be72877c74f257b561b19
713 <highlight language="lua">
714 r:escape(string) -- URL-Escapes a string:
716 local url = "http://foo.bar/1 2 3 & 4 + 5"
717 local escaped = r:escape(url) -- returns 'http%3a%2f%2ffoo.bar%2f1+2+3+%26+4+%2b+5'
720 <highlight language="lua">
721 r:unescape(string) -- Unescapes an URL-escaped string:
723 local url = "http%3a%2f%2ffoo.bar%2f1+2+3+%26+4+%2b+5"
724 local unescaped = r:unescape(url) -- returns 'http://foo.bar/1 2 3 & 4 + 5'
727 <highlight language="lua">
728 r:construct_url(string) -- Constructs an URL from an URI
730 local url = r:construct_url(r.uri)
733 <highlight language="lua">
734 r.mpm_query(number) -- Queries the server for MPM information using ap_mpm_query:
736 local mpm = r.mpm_query(14)
738 r:puts("This server uses the Event MPM")
742 <highlight language="lua">
743 r:expr(string) -- Evaluates an <a href="../expr.html">expr</a> string.
745 if r:expr("%{HTTP_HOST} =~ /^www/") then
746 r:puts("This host name starts with www")
750 <highlight language="lua">
751 r:scoreboard_process(a) -- Queries the server for information about the process at position <code>a</code>:
753 local process = r:scoreboard_process(1)
754 r:puts("Server 1 has PID " .. process.pid)
757 <highlight language="lua">
758 r:scoreboard_worker(a, b) -- Queries for information about the worker thread, <code>b</code>, in process <code>a</code>:
760 local thread = r:scoreboard_worker(1, 1)
761 r:puts("Server 1's thread 1 has thread ID " .. thread.tid .. " and is in " .. thread.status .. " status")
765 <highlight language="lua">
766 r:clock() -- Returns the current time with microsecond precision
769 <highlight language="lua">
770 r:requestbody(filename) -- Reads and returns the request body of a request.
771 -- If 'filename' is specified, it instead saves the
772 -- contents to that file:
774 local input = r:requestbody()
775 r:puts("You sent the following request body to me:\n")
779 <highlight language="lua">
780 r:add_input_filter(filter_name) -- Adds 'filter_name' as an input filter
783 <highlight language="lua">
784 r.module_info(module_name) -- Queries the server for information about a module
786 local mod = r.module_info("mod_lua.c")
788 for k, v in pairs(mod.commands) do
789 r:puts( ("%s: %s\n"):format(k,v)) -- print out all directives accepted by this module
794 <highlight language="lua">
795 r:loaded_modules() -- Returns a list of modules loaded by httpd:
797 for k, module in pairs(r:loaded_modules()) do
798 r:puts("I have loaded module " .. module .. "\n")
802 <highlight language="lua">
803 r:runtime_dir_relative(filename) -- Compute the name of a run-time file (e.g., shared memory "file")
804 -- relative to the appropriate run-time directory.
807 <highlight language="lua">
808 r:server_info() -- Returns a table containing server information, such as
809 -- the name of the httpd executable file, mpm used etc.
812 <highlight language="lua">
813 r:set_document_root(file_path) -- Sets the document root for the request to file_path
817 <highlight language="lua">
818 r:add_version_component(component_string) - - Adds a component to the server banner.
822 <highlight language="lua">
823 r:set_context_info(prefix, docroot) -- Sets the context prefix and context document root for a request
826 <highlight language="lua">
827 r:os_escape_path(file_path) -- Converts an OS path to a URL in an OS dependent way
830 <highlight language="lua">
831 r:escape_logitem(string) -- Escapes a string for logging
834 <highlight language="lua">
835 r.strcmp_match(string, pattern) -- Checks if 'string' matches 'pattern' using strcmp_match (globs).
836 -- fx. whether 'www.example.com' matches '*.example.com':
838 local match = r.strcmp_match("foobar.com", "foo*.com")
840 r:puts("foobar.com matches foo*.com")
844 <highlight language="lua">
845 r:set_keepalive() -- Sets the keepalive status for a request. Returns true if possible, false otherwise.
848 <highlight language="lua">
849 r:make_etag() -- Constructs and returns the etag for the current request.
852 <highlight language="lua">
853 r:send_interim_response(clear) -- Sends an interim (1xx) response to the client.
854 -- if 'clear' is true, available headers will be sent and cleared.
857 <highlight language="lua">
858 r:custom_response(status_code, string) -- Construct and set a custom response for a given status code.
859 -- This works much like the ErrorDocument directive:
861 r:custom_response(404, "Baleted!")
864 <highlight language="lua">
865 r.exists_config_define(string) -- Checks whether a configuration definition exists or not:
867 if r.exists_config_define("FOO") then
868 r:puts("httpd was probably run with -DFOO, or it was defined in the configuration")
872 <highlight language="lua">
873 r:state_query(string) -- Queries the server for state information
876 <highlight language="lua">
877 r:stat(filename [,wanted]) -- Runs stat() on a file, and returns a table with file information:
879 local info = r:stat("/var/www/foo.txt")
881 r:puts("This file exists and was last modified at: " .. info.modified)
885 <highlight language="lua">
886 r:regex(string, pattern [,flags]) -- Runs a regular expression match on a string, returning captures if matched:
888 local matches = r:regex("foo bar baz", [[foo (\w+) (\S*)]])
890 r:puts("The regex matched, and the last word captured ($2) was: " .. matches[2])
893 -- Example ignoring case sensitivity:
894 local matches = r:regex("FOO bar BAz", [[(foo) bar]], 1)
896 -- Flags can be a bitwise combination of:
898 -- 0x02: Multiline search
901 <highlight language="lua">
902 r.usleep(number_of_microseconds) -- Puts the script to sleep for a given number of microseconds.
905 <highlight language="lua">
906 r:dbacquire(dbType[, dbParams]) -- Acquires a connection to a database and returns a database class.
907 -- See '<a href="#databases">Database connectivity</a>' for details.
910 <highlight language="lua">
911 r:ivm_set("key", value) -- Set an Inter-VM variable to hold a specific value.
912 -- These values persist even though the VM is gone or not being used,
913 -- and so should only be used if MaxConnectionsPerChild is > 0
914 -- Values can be numbers, strings and booleans, and are stored on a
915 -- per process basis (so they won't do much good with a prefork mpm)
917 r:ivm_get("key") -- Fetches a variable set by ivm_set. Returns the contents of the variable
918 -- if it exists or nil if no such variable exists.
920 -- An example getter/setter that saves a global variable outside the VM:
922 -- First VM to call this will get no value, and will have to create it
923 local foo = r:ivm_get("cached_data")
925 foo = do_some_calcs() -- fake some return value
926 r:ivm_set("cached_data", foo) -- set it globally
928 r:puts("Cached data is: ", foo)
932 <highlight language="lua">
933 r:htpassword(string [,algorithm [,cost]]) -- Creates a password hash from a string.
934 -- algorithm: 0 = APMD5 (default), 1 = SHA, 2 = BCRYPT, 3 = CRYPT.
935 -- cost: only valid with BCRYPT algorithm (default = 5).
938 <highlight language="lua">
939 r:mkdir(dir [,mode]) -- Creates a directory and sets mode to optional mode parameter.
942 <highlight language="lua">
943 r:mkrdir(dir [,mode]) -- Creates directories recursive and sets mode to optional mode parameter.
946 <highlight language="lua">
947 r:rmdir(dir) -- Removes a directory.
950 <highlight language="lua">
951 r:touch(file [,mtime]) -- Sets the file modification time to current time or to optional mtime msec value.
954 <highlight language="lua">
955 r:get_direntries(dir) -- Returns a table with all directory entries.
958 local dir = r.context_document_root
959 for _, f in ipairs(r:get_direntries(dir)) do
960 local info = r:stat(dir .. "/" .. f)
962 local mtime = os.date(fmt, info.mtime / 1000000)
963 local ftype = (info.filetype == 2) and "[dir] " or "[file]"
964 r:puts( ("%s %s %10i %s\n"):format(ftype, mtime, info.size, f) )
970 <highlight language="lua">
971 r.date_parse_rfc(string) -- Parses a date/time string and returns seconds since epoche.
974 <highlight language="lua">
975 r:getcookie(key) -- Gets a HTTP cookie
978 <highlight language="lua">
984 httponly = [boolean],
987 } -- Sets a HTTP cookie, for instance:
991 value = "HDHfa9eyffh396rt",
992 expires = os.time() + 86400,
997 <highlight language="lua">
998 r:wsupgrade() -- Upgrades a connection to WebSockets if possible (and requested):
999 if r:wsupgrade() then -- if we can upgrade:
1000 r:wswrite("Welcome to websockets!") -- write something to the client
1001 r:wsclose() -- goodbye!
1005 <highlight language="lua">
1006 r:wsread() -- Reads a WebSocket frame from a WebSocket upgraded connection (see above):
1008 local line, isFinal = r:wsread() -- isFinal denotes whether this is the final frame.
1009 -- If it isn't, then more frames can be read
1010 r:wswrite("You wrote: " .. line)
1013 <highlight language="lua">
1014 r:wswrite(line) -- Writes a frame to a WebSocket client:
1015 r:wswrite("Hello, world!")
1018 <highlight language="lua">
1019 r:wsclose() -- Closes a WebSocket request and terminates it for httpd:
1021 if r:wsupgrade() then
1022 r:wswrite("Write something: ")
1023 local line = r:wsread() or "nothing"
1024 r:wswrite("You wrote: " .. line);
1025 r:wswrite("Goodbye!")
1030 <highlight language="lua">
1031 r:wspeek() -- Checks if any data is ready to be read
1033 -- Sleep while nothing is being sent to us...
1034 while r:wspeek() == false do
1037 -- We have data ready!
1038 local line = r:wsread()
1043 <highlight language="lua">
1044 r:config() -- Get a walkable tree of the entire httpd configuration
1047 <highlight language="lua">
1048 r:activeconfig() -- Get a walkable tree of the active (virtualhost-specific) httpd configuration
1054 <section id="logging"><title>Logging Functions</title>
1056 <highlight language="lua">
1057 -- examples of logging messages
1058 r:trace1("This is a trace log message") -- trace1 through trace8 can be used
1059 r:debug("This is a debug log message")
1060 r:info("This is an info log message")
1061 r:notice("This is a notice log message")
1062 r:warn("This is a warn log message")
1063 r:err("This is an err log message")
1064 r:alert("This is an alert log message")
1065 r:crit("This is a crit log message")
1066 r:emerg("This is an emerg log message")
1071 <section id="apache2"><title>apache2 Package</title>
1072 <p>A package named <code>apache2</code> is available with (at least) the following contents.</p>
1075 <dd>internal constant OK. Handlers should return this if they've
1076 handled the request.</dd>
1077 <dt>apache2.DECLINED</dt>
1078 <dd>internal constant DECLINED. Handlers should return this if
1079 they are not going to handle the request.</dd>
1080 <dt>apache2.DONE</dt>
1081 <dd>internal constant DONE.</dd>
1082 <dt>apache2.version</dt>
1083 <dd>Apache HTTP server version string</dd>
1084 <dt>apache2.HTTP_MOVED_TEMPORARILY</dt>
1085 <dd>HTTP status code</dd>
1086 <dt>apache2.PROXYREQ_NONE, apache2.PROXYREQ_PROXY, apache2.PROXYREQ_REVERSE, apache2.PROXYREQ_RESPONSE</dt>
1087 <dd>internal constants used by <module>mod_proxy</module></dd>
1088 <dt>apache2.AUTHZ_DENIED, apache2.AUTHZ_GRANTED, apache2.AUTHZ_NEUTRAL, apache2.AUTHZ_GENERAL_ERROR, apache2.AUTHZ_DENIED_NO_USER</dt>
1089 <dd>internal constants used by <module>mod_authz_core</module></dd>
1092 <p>(Other HTTP status codes are not yet implemented.)</p>
1095 <section id="modifying_buckets">
1096 <title>Modifying contents with Lua filters</title>
1098 Filter functions implemented via <directive module="mod_lua">LuaInputFilter</directive>
1099 or <directive module="mod_lua">LuaOutputFilter</directive> are designed as
1100 three-stage non-blocking functions using coroutines to suspend and resume a
1101 function as buckets are sent down the filter chain. The core structure of
1104 <highlight language="lua">
1106 -- Our first yield is to signal that we are ready to receive buckets.
1107 -- Before this yield, we can set up our environment, check for conditions,
1108 -- and, if we deem it necessary, decline filtering a request alltogether:
1109 if something_bad then
1110 return -- This would skip this filter.
1112 -- Regardless of whether we have data to prepend, a yield MUST be called here.
1113 -- Note that only output filters can prepend data. Input filters must use the
1114 -- final stage to append data to the content.
1115 coroutine.yield([optional header to be prepended to the content])
1117 -- After we have yielded, buckets will be sent to us, one by one, and we can
1118 -- do whatever we want with them and then pass on the result.
1119 -- Buckets are stored in the global variable 'bucket', so we create a loop
1120 -- that checks if 'bucket' is not nil:
1121 while bucket ~= nil do
1122 local output = mangle(bucket) -- Do some stuff to the content
1123 coroutine.yield(output) -- Return our new content to the filter chain
1126 -- Once the buckets are gone, 'bucket' is set to nil, which will exit the
1127 -- loop and land us here. Anything extra we want to append to the content
1128 -- can be done by doing a final yield here. Both input and output filters
1129 -- can append data to the content in this phase.
1130 coroutine.yield([optional footer to be appended to the content])
1135 <section id="databases">
1136 <title>Database connectivity</title>
1138 Mod_lua implements a simple database feature for querying and running commands
1139 on the most popular database engines (mySQL, PostgreSQL, FreeTDS, ODBC, SQLite, Oracle)
1142 <p>The example below shows how to acquire a database handle and return information from a table:</p>
1143 <highlight language="lua">
1145 -- Acquire a database handle
1146 local database, err = r:dbacquire("mysql", "server=localhost,user=someuser,pass=somepass,dbname=mydb")
1148 -- Select some information from it
1149 local results, err = database:select(r, "SELECT `name`, `age` FROM `people` WHERE 1")
1151 local rows = results(0) -- fetch all rows synchronously
1152 for k, row in pairs(rows) do
1153 r:puts( string.format("Name: %s, Age: %s<br/>", row[1], row[2]) )
1156 r:puts("Database query error: " .. err)
1160 r:puts("Could not connect to the database: " .. err)
1165 To utilize <module>mod_dbd</module>, specify <code>mod_dbd</code>
1166 as the database type, or leave the field blank:
1168 <highlight language="lua">
1169 local database = r:dbacquire("mod_dbd")
1171 <section id="database_object">
1172 <title>Database object and contained functions</title>
1173 <p>The database object returned by <code>dbacquire</code> has the following methods:</p>
1174 <p><strong>Normal select and query from a database:</strong></p>
1175 <highlight language="lua">
1176 -- Run a statement and return the number of rows affected:
1177 local affected, errmsg = database:query(r, "DELETE FROM `tbl` WHERE 1")
1179 -- Run a statement and return a result set that can be used synchronously or async:
1180 local result, errmsg = database:select(r, "SELECT * FROM `people` WHERE 1")
1182 <p><strong>Using prepared statements (recommended):</strong></p>
1183 <highlight language="lua">
1184 -- Create and run a prepared statement:
1185 local statement, errmsg = database:prepare(r, "DELETE FROM `tbl` WHERE `age` > %u")
1187 local result, errmsg = statement:query(20) -- run the statement with age > 20
1190 -- Fetch a prepared statement from a DBDPrepareSQL directive:
1191 local statement, errmsg = database:prepared(r, "someTag")
1193 local result, errmsg = statement:select("John Doe", 123) -- inject the values "John Doe" and 123 into the statement
1197 <p><strong>Escaping values, closing databases etc:</strong></p>
1198 <highlight language="lua">
1199 -- Escape a value for use in a statement:
1200 local escaped = database:escape(r, [["'|blabla]])
1202 -- Close a database connection and free up handles:
1205 -- Check whether a database connection is up and running:
1206 local connected = database:active()
1209 <section id="result_sets">
1210 <title>Working with result sets</title>
1211 <p>The result set returned by <code>db:select</code> or by the prepared statement functions
1212 created through <code>db:prepare</code> can be used to
1213 fetch rows synchronously or asynchronously, depending on the row number specified:<br/>
1214 <code>result(0)</code> fetches all rows in a synchronous manner, returning a table of rows.<br/>
1215 <code>result(-1)</code> fetches the next available row in the set, asynchronously.<br/>
1216 <code>result(N)</code> fetches row number <code>N</code>, asynchronously:
1218 <highlight language="lua">
1219 -- fetch a result set using a regular query:
1220 local result, err = db:select(r, "SELECT * FROM `tbl` WHERE 1")
1222 local rows = result(0) -- Fetch ALL rows synchronously
1223 local row = result(-1) -- Fetch the next available row, asynchronously
1224 local row = result(1234) -- Fetch row number 1234, asynchronously
1225 local row = result(-1, true) -- Fetch the next available row, using row names as key indexes.
1227 <p>One can construct a function that returns an iterative function to iterate over all rows
1228 in a synchronous or asynchronous way, depending on the async argument:
1230 <highlight language="lua">
1231 function rows(resultset, async)
1233 local function getnext()
1235 local row = resultset(-1)
1236 return row and a or nil, row
1239 return pairs(resultset(0))
1241 return getnext, self
1245 local statement, err = db:prepare(r, "SELECT * FROM `tbl` WHERE `age` > %u")
1247 -- fetch rows asynchronously:
1248 local result, err = statement:select(20)
1250 for index, row in rows(result, true) do
1255 -- fetch rows synchronously:
1256 local result, err = statement:select(20)
1258 for index, row in rows(result, false) do
1265 <section id="closing_databases">
1266 <title>Closing a database connection</title>
1268 <p>Database handles should be closed using <code>database:close()</code> when they are no longer
1269 needed. If you do not close them manually, they will eventually be garbage collected and
1270 closed by mod_lua, but you may end up having too many unused connections to the database
1271 if you leave the closing up to mod_lua. Essentially, the following two measures are
1274 <highlight language="lua">
1275 -- Method 1: Manually close a handle
1276 local database = r:dbacquire("mod_dbd")
1277 database:close() -- All done
1279 -- Method 2: Letting the garbage collector close it
1280 local database = r:dbacquire("mod_dbd")
1281 database = nil -- throw away the reference
1282 collectgarbage() -- close the handle via GC
1285 <section id="database_caveat">
1286 <title>Precautions when working with databases</title>
1287 <p>Although the standard <code>query</code> and <code>run</code> functions are freely
1288 available, it is recommended that you use prepared statements whenever possible, to
1289 both optimize performance (if your db handle lives on for a long time) and to minimize
1290 the risk of SQL injection attacks. <code>run</code> and <code>query</code> should only
1291 be used when there are no variables inserted into a statement (a static statement).
1292 When using dynamic statements, use <code>db:prepare</code> or <code>db:prepared</code>.
1299 <name>LuaRoot</name>
1300 <description>Specify the base path for resolving relative paths for mod_lua directives</description>
1301 <syntax>LuaRoot /path/to/a/directory</syntax>
1302 <contextlist><context>server config</context><context>virtual host</context>
1303 <context>directory</context><context>.htaccess</context>
1305 <override>All</override>
1308 <p>Specify the base path which will be used to evaluate all
1309 relative paths within mod_lua. If not specified they
1310 will be resolved relative to the current working directory,
1311 which may not always work well for a server.</p>
1313 </directivesynopsis>
1316 <name>LuaScope</name>
1317 <description>One of once, request, conn, thread -- default is once</description>
1318 <syntax>LuaScope once|request|conn|thread|server [min] [max]</syntax>
1319 <default>LuaScope once</default>
1320 <contextlist><context>server config</context><context>virtual host</context>
1321 <context>directory</context><context>.htaccess</context>
1323 <override>All</override>
1326 <p>Specify the life cycle scope of the Lua interpreter which will
1327 be used by handlers in this "Directory." The default is "once"</p>
1330 <dt>once:</dt> <dd>use the interpreter once and throw it away.</dd>
1332 <dt>request:</dt> <dd>use the interpreter to handle anything based on
1333 the same file within this request, which is also
1334 request scoped.</dd>
1336 <dt>conn:</dt> <dd>Same as request but attached to the connection_rec</dd>
1338 <dt>thread:</dt> <dd>Use the interpreter for the lifetime of the thread
1339 handling the request (only available with threaded MPMs).</dd>
1341 <dt>server:</dt> <dd>This one is different than others because the
1342 server scope is quite long lived, and multiple threads
1343 will have the same server_rec. To accommodate this,
1344 server scoped Lua states are stored in an apr
1345 resource list. The <code>min</code> and <code>max</code> arguments
1346 specify the minimum and maximum number of Lua states to keep in the
1350 Generally speaking, the <code>thread</code> and <code>server</code> scopes
1351 execute roughly 2-3 times faster than the rest, because they don't have to
1352 spawn new Lua states on every request (especially with the event MPM, as
1353 even keepalive requests will use a new thread for each request). If you are
1354 satisfied that your scripts will not have problems reusing a state, then
1355 the <code>thread</code> or <code>server</code> scopes should be used for
1356 maximum performance. While the <code>thread</code> scope will provide the
1357 fastest responses, the <code>server</code> scope will use less memory, as
1358 states are pooled, allowing f.x. 1000 threads to share only 100 Lua states,
1359 thus using only 10% of the memory required by the <code>thread</code> scope.
1362 </directivesynopsis>
1365 <name>LuaMapHandler</name>
1366 <description>Map a path to a lua handler</description>
1367 <syntax>LuaMapHandler uri-pattern /path/to/lua/script.lua [function-name]</syntax>
1368 <contextlist><context>server config</context><context>virtual host</context>
1369 <context>directory</context><context>.htaccess</context>
1371 <override>All</override>
1373 <p>This directive matches a uri pattern to invoke a specific
1374 handler function in a specific file. It uses PCRE regular
1375 expressions to match the uri, and supports interpolating
1376 match groups into both the file path and the function name.
1377 Be careful writing your regular expressions to avoid security
1379 <example><title>Examples:</title>
1380 <highlight language="config">
1381 LuaMapHandler /(\w+)/(\w+) /scripts/$1.lua handle_$2
1384 <p>This would match uri's such as /photos/show?id=9
1385 to the file /scripts/photos.lua and invoke the
1386 handler function handle_show on the lua vm after
1387 loading that file.</p>
1389 <highlight language="config">
1390 LuaMapHandler /bingo /scripts/wombat.lua
1392 <p>This would invoke the "handle" function, which
1393 is the default if no specific function name is
1396 </directivesynopsis>
1399 <name>LuaPackagePath</name>
1400 <description>Add a directory to lua's package.path</description>
1401 <syntax>LuaPackagePath /path/to/include/?.lua</syntax>
1402 <contextlist><context>server config</context><context>virtual host</context>
1403 <context>directory</context><context>.htaccess</context>
1405 <override>All</override>
1406 <usage><p>Add a path to lua's module search path. Follows the same
1407 conventions as lua. This just munges the package.path in the
1410 <example><title>Examples:</title>
1411 <highlight language="config">
1412 LuaPackagePath /scripts/lib/?.lua
1413 LuaPackagePath /scripts/lib/?/init.lua
1417 </directivesynopsis>
1420 <name>LuaPackageCPath</name>
1421 <description>Add a directory to lua's package.cpath</description>
1422 <syntax>LuaPackageCPath /path/to/include/?.soa</syntax>
1423 <contextlist><context>server config</context><context>virtual host</context>
1424 <context>directory</context><context>.htaccess</context>
1426 <override>All</override>
1429 <p>Add a path to lua's shared library search path. Follows the same
1430 conventions as lua. This just munges the package.cpath in the
1434 </directivesynopsis>
1437 <name>LuaCodeCache</name>
1438 <description>Configure the compiled code cache.</description>
1439 <syntax>LuaCodeCache stat|forever|never</syntax>
1440 <default>LuaCodeCache stat</default>
1442 <context>server config</context><context>virtual host</context>
1443 <context>directory</context><context>.htaccess</context>
1445 <override>All</override>
1448 Specify the behavior of the in-memory code cache. The default
1449 is stat, which stats the top level script (not any included
1450 ones) each time that file is needed, and reloads it if the
1451 modified time indicates it is newer than the one it has
1452 already loaded. The other values cause it to keep the file
1453 cached forever (don't stat and replace) or to never cache the
1456 <p>In general stat or forever is good for production, and stat or never
1457 for development.</p>
1459 <example><title>Examples:</title>
1460 <highlight language="config">
1462 LuaCodeCache forever
1468 </directivesynopsis>
1471 <name>LuaHookTranslateName</name>
1472 <description>Provide a hook for the translate name phase of request processing</description>
1473 <syntax>LuaHookTranslateName /path/to/lua/script.lua hook_function_name [early|late]</syntax>
1474 <contextlist><context>server config</context><context>virtual host</context>
1476 <override>All</override>
1477 <compatibility>The optional third argument is supported in 2.3.15 and later</compatibility>
1480 Add a hook (at APR_HOOK_MIDDLE) to the translate name phase of
1481 request processing. The hook function receives a single
1482 argument, the request_rec, and should return a status code,
1483 which is either an HTTP error code, or the constants defined
1484 in the apache2 module: apache2.OK, apache2.DECLINED, or
1487 <p>For those new to hooks, basically each hook will be invoked
1488 until one of them returns apache2.OK. If your hook doesn't
1489 want to do the translation it should just return
1490 apache2.DECLINED. If the request should stop processing, then
1491 return apache2.DONE.</p>
1495 <highlight language="config">
1497 LuaHookTranslateName /scripts/conf/hooks.lua silly_mapper
1500 <highlight language="lua">
1501 -- /scripts/conf/hooks.lua --
1503 function silly_mapper(r)
1504 if r.uri == "/" then
1505 r.filename = "/var/www/home.lua"
1508 return apache2.DECLINED
1513 <note><title>Context</title><p>This directive is not valid in <directive
1514 type="section" module="core">Directory</directive>, <directive
1515 type="section" module="core">Files</directive>, or htaccess
1518 <note><title>Ordering</title><p>The optional arguments "early" or "late"
1519 control when this script runs relative to other modules.</p></note>
1522 </directivesynopsis>
1525 <name>LuaHookFixups</name>
1526 <description>Provide a hook for the fixups phase of a request
1527 processing</description>
1528 <syntax>LuaHookFixups /path/to/lua/script.lua hook_function_name</syntax>
1529 <contextlist><context>server config</context><context>virtual host</context>
1530 <context>directory</context><context>.htaccess</context>
1532 <override>All</override>
1535 Just like LuaHookTranslateName, but executed at the fixups phase
1538 </directivesynopsis>
1541 <name>LuaHookLog</name>
1542 <description>Provide a hook for the access log phase of a request
1543 processing</description>
1544 <syntax>LuaHookLog /path/to/lua/script.lua log_function_name</syntax>
1545 <contextlist><context>server config</context><context>virtual host</context>
1546 <context>directory</context><context>.htaccess</context>
1548 <override>All</override>
1551 This simple logging hook allows you to run a function when httpd enters the
1552 logging phase of a request. With it, you can append data to your own logs,
1553 manipulate data before the regular log is written, or prevent a log entry
1554 from being created. To prevent the usual logging from happening, simply return
1555 <code>apache2.DONE</code> in your logging handler, otherwise return
1556 <code>apache2.OK</code> to tell httpd to log as normal.
1559 <highlight language="config">
1560 LuaHookLog /path/to/script.lua logger
1562 <highlight language="lua">
1563 -- /path/to/script.lua --
1566 -- If 1, then we write to our own Lua log and tell httpd not to log
1568 -- If 2, then we just sanitize the output a bit and tell httpd to
1569 -- log the sanitized bits.
1571 if math.random(1,2) == 1 then
1572 -- Log stuff ourselves and don't log in the regular log
1573 local f = io.open("/foo/secret.log", "a")
1575 f:write("Something secret happened at " .. r.uri .. "\n")
1578 return apache2.DONE -- Tell httpd not to use the regular logging functions
1580 r.uri = r.uri:gsub("somesecretstuff", "") -- sanitize the URI
1581 return apache2.OK -- tell httpd to log it.
1586 </directivesynopsis>
1590 <name>LuaHookMapToStorage</name>
1591 <description>Provide a hook for the map_to_storage phase of request processing</description>
1592 <syntax>LuaHookMapToStorage /path/to/lua/script.lua hook_function_name</syntax>
1593 <contextlist><context>server config</context><context>virtual host</context>
1594 <context>directory</context><context>.htaccess</context>
1596 <override>All</override>
1598 <p>Like <directive>LuaHookTranslateName</directive> but executed at the
1599 map-to-storage phase of a request. Modules like mod_cache run at this phase,
1600 which makes for an interesting example on what to do here:</p>
1601 <highlight language="config">
1602 LuaHookMapToStorage /path/to/lua/script.lua check_cache
1604 <highlight language="lua">
1608 function read_file(filename)
1609 local input = io.open(filename, "r")
1611 local data = input:read("*a")
1612 cached_files[filename] = data
1613 file = cached_files[filename]
1616 return cached_files[filename]
1619 function check_cache(r)
1620 if r.filename:match("%.png$") then -- Only match PNG files
1621 local file = cached_files[r.filename] -- Check cache entries
1623 file = read_file(r.filename) -- Read file into cache
1625 if file then -- If file exists, write it out
1628 r:info(("Sent %s to client from cache"):format(r.filename))
1629 return apache2.DONE -- skip default handler for PNG files
1632 return apache2.DECLINED -- If we had nothing to do, let others serve this.
1637 </directivesynopsis>
1640 <name>LuaHookCheckUserID</name>
1641 <description>Provide a hook for the check_user_id phase of request processing</description>
1642 <syntax>LuaHookCheckUserID /path/to/lua/script.lua hook_function_name</syntax>
1643 <contextlist><context>server config</context><context>virtual host</context>
1644 <context>directory</context><context>.htaccess</context>
1646 <override>All</override>
1647 <!-- Third argument does not work at the moment!
1648 <compatibility>The optional third argument is supported in 2.3.15 and later</compatibility>
1650 <note><title>Ordering</title><p>The optional arguments "early" or "late"
1651 control when this script runs relative to other modules.</p></note>
1654 </directivesynopsis>
1657 <name>LuaHookTypeChecker</name>
1658 <description>Provide a hook for the type_checker phase of request processing</description>
1659 <syntax>LuaHookTypeChecker /path/to/lua/script.lua hook_function_name</syntax>
1660 <contextlist><context>server config</context><context>virtual host</context>
1661 <context>directory</context><context>.htaccess</context>
1663 <override>All</override>
1665 This directive provides a hook for the type_checker phase of the request processing.
1666 This phase is where requests are assigned a content type and a handler, and thus can
1667 be used to modify the type and handler based on input:
1669 <highlight language="config">
1670 LuaHookTypeChecker /path/to/lua/script.lua type_checker
1672 <highlight language="lua">
1673 function type_checker(r)
1674 if r.uri:match("%.to_gif$") then -- match foo.png.to_gif
1675 r.content_type = "image/gif" -- assign it the image/gif type
1676 r.handler = "gifWizard" -- tell the gifWizard module to handle this
1677 r.filename = r.uri:gsub("%.to_gif$", "") -- fix the filename requested
1681 return apache2.DECLINED
1685 </directivesynopsis>
1688 <name>LuaHookAuthChecker</name>
1689 <description>Provide a hook for the auth_checker phase of request processing</description>
1690 <syntax>LuaHookAuthChecker /path/to/lua/script.lua hook_function_name [early|late]</syntax>
1691 <contextlist><context>server config</context><context>virtual host</context>
1692 <context>directory</context><context>.htaccess</context>
1694 <override>All</override>
1695 <compatibility>The optional third argument is supported in 2.3.15 and later</compatibility>
1697 <p>Invoke a lua function in the auth_checker phase of processing
1698 a request. This can be used to implement arbitrary authentication
1699 and authorization checking. A very simple example:
1701 <highlight language="lua">
1704 -- fake authcheck hook
1705 -- If request has no auth info, set the response header and
1706 -- return a 401 to ask the browser for basic auth info.
1707 -- If request has auth info, don't actually look at it, just
1708 -- pretend we got userid 'foo' and validated it.
1709 -- Then check if the userid is 'foo' and accept the request.
1710 function authcheck_hook(r)
1712 -- look for auth info
1713 auth = r.headers_in['Authorization']
1719 if r.user == nil then
1720 r:debug("authcheck: user is nil, returning 401")
1721 r.err_headers_out['WWW-Authenticate'] = 'Basic realm="WallyWorld"'
1723 elseif r.user == "foo" then
1724 r:debug('user foo: OK')
1726 r:debug("authcheck: user='" .. r.user .. "'")
1727 r.err_headers_out['WWW-Authenticate'] = 'Basic realm="WallyWorld"'
1733 <note><title>Ordering</title><p>The optional arguments "early" or "late"
1734 control when this script runs relative to other modules.</p></note>
1736 </directivesynopsis>
1739 <name>LuaHookAccessChecker</name>
1740 <description>Provide a hook for the access_checker phase of request processing</description>
1741 <syntax>LuaHookAccessChecker /path/to/lua/script.lua hook_function_name [early|late]</syntax>
1742 <contextlist><context>server config</context><context>virtual host</context>
1743 <context>directory</context><context>.htaccess</context>
1745 <override>All</override>
1746 <compatibility>The optional third argument is supported in 2.3.15 and later</compatibility>
1748 <p>Add your hook to the access_checker phase. An access checker
1749 hook function usually returns OK, DECLINED, or HTTP_FORBIDDEN.</p>
1750 <note><title>Ordering</title><p>The optional arguments "early" or "late"
1751 control when this script runs relative to other modules.</p></note>
1753 </directivesynopsis>
1756 <name>LuaHookInsertFilter</name>
1757 <description>Provide a hook for the insert_filter phase of request processing</description>
1758 <syntax>LuaHookInsertFilter /path/to/lua/script.lua hook_function_name</syntax>
1759 <contextlist><context>server config</context><context>virtual host</context>
1760 <context>directory</context><context>.htaccess</context>
1762 <override>All</override>
1763 <usage><p>Not Yet Implemented</p></usage>
1764 </directivesynopsis>
1767 <name>LuaInherit</name>
1768 <description>Controls how parent configuration sections are merged into children</description>
1769 <syntax>LuaInherit none|parent-first|parent-last</syntax>
1770 <default>LuaInherit parent-first</default>
1771 <contextlist><context>server config</context><context>virtual host</context>
1772 <context>directory</context><context>.htaccess</context>
1774 <override>All</override>
1775 <compatibility>2.4.0 and later</compatibility>
1776 <usage><p>By default, if LuaHook* directives are used in overlapping
1777 Directory or Location configuration sections, the scripts defined in the
1778 more specific section are run <em>after</em> those defined in the more
1779 generic section (LuaInherit parent-first). You can reverse this order, or
1780 make the parent context not apply at all.</p>
1782 <p> In previous 2.3.x releases, the default was effectively to ignore LuaHook*
1783 directives from parent configuration sections.</p></usage>
1784 </directivesynopsis>
1787 <name>LuaQuickHandler</name>
1788 <description>Provide a hook for the quick handler of request processing</description>
1789 <syntax>LuaQuickHandler /path/to/script.lua hook_function_name</syntax>
1790 <contextlist><context>server config</context><context>virtual host</context>
1792 <override>All</override>
1795 This phase is run immediately after the request has been mapped to a virtal host,
1796 and can be used to either do some request processing before the other phases kick
1797 in, or to serve a request without the need to translate, map to storage et cetera.
1798 As this phase is run before anything else, directives such as <directive
1799 type="section" module="core">Location</directive> or <directive
1800 type="section" module="core">Directory</directive> are void in this phase, just as
1801 URIs have not been properly parsed yet.
1803 <note><title>Context</title><p>This directive is not valid in <directive
1804 type="section" module="core">Directory</directive>, <directive
1805 type="section" module="core">Files</directive>, or htaccess
1808 </directivesynopsis>
1811 <name>LuaAuthzProvider</name>
1812 <description>Plug an authorization provider function into <module>mod_authz_core</module>
1814 <syntax>LuaAuthzProvider provider_name /path/to/lua/script.lua function_name</syntax>
1815 <contextlist><context>server config</context> </contextlist>
1816 <compatibility>2.4.3 and later</compatibility>
1819 <p>After a lua function has been registered as authorization provider, it can be used
1820 with the <directive module="mod_authz_core">Require</directive> directive:</p>
1822 <highlight language="config">
1823 LuaRoot /usr/local/apache2/lua
1824 LuaAuthzProvider foo authz.lua authz_check_foo
1825 <Location "/">
1829 <highlight language="lua">
1831 function authz_check_foo(r, who)
1832 if r.user ~= who then return apache2.AUTHZ_DENIED
1833 return apache2.AUTHZ_GRANTED
1839 </directivesynopsis>
1843 <name>LuaInputFilter</name>
1844 <description>Provide a Lua function for content input filtering</description>
1845 <syntax>LuaInputFilter filter_name /path/to/lua/script.lua function_name</syntax>
1846 <contextlist><context>server config</context> </contextlist>
1847 <override>All</override>
1848 <compatibility>2.4.5 and later</compatibility>
1851 <p>Provides a means of adding a Lua function as an input filter.
1852 As with output filters, input filters work as coroutines,
1853 first yielding before buffers are sent, then yielding whenever
1854 a bucket needs to be passed down the chain, and finally (optionally)
1855 yielding anything that needs to be appended to the input data. The
1856 global variable <code>bucket</code> holds the buckets as they are passed
1857 onto the Lua script:
1860 <highlight language="config">
1861 LuaInputFilter myInputFilter /www/filter.lua input_filter
1862 <Files "*.lua">
1863 SetInputFilter myInputFilter
1866 <highlight language="lua">
1868 Example input filter that converts all POST data to uppercase.
1870 function input_filter(r)
1871 print("luaInputFilter called") -- debug print
1872 coroutine.yield() -- Yield and wait for buckets
1873 while bucket do -- For each bucket, do...
1874 local output = string.upper(bucket) -- Convert all POST data to uppercase
1875 coroutine.yield(output) -- Send converted data down the chain
1877 -- No more buckets available.
1878 coroutine.yield("&filterSignature=1234") -- Append signature at the end
1882 The input filter supports denying/skipping a filter if it is deemed unwanted:
1884 <highlight language="lua">
1885 function input_filter(r)
1887 return -- Simply deny filtering, passing on the original content instead
1889 coroutine.yield() -- wait for buckets
1890 ... -- insert filter stuff here
1894 See "<a href="#modifying_buckets">Modifying contents with Lua
1895 filters</a>" for more information.
1898 </directivesynopsis>
1901 <name>LuaOutputFilter</name>
1902 <description>Provide a Lua function for content output filtering</description>
1903 <syntax>LuaOutputFilter filter_name /path/to/lua/script.lua function_name</syntax>
1904 <contextlist><context>server config</context> </contextlist>
1905 <override>All</override>
1906 <compatibility>2.4.5 and later</compatibility>
1909 <p>Provides a means of adding a Lua function as an output filter.
1910 As with input filters, output filters work as coroutines,
1911 first yielding before buffers are sent, then yielding whenever
1912 a bucket needs to be passed down the chain, and finally (optionally)
1913 yielding anything that needs to be appended to the input data. The
1914 global variable <code>bucket</code> holds the buckets as they are passed
1915 onto the Lua script:
1918 <highlight language="config">
1919 LuaOutputFilter myOutputFilter /www/filter.lua output_filter
1920 <Files "*.lua">
1921 SetOutputFilter myOutputFilter
1924 <highlight language="lua">
1926 Example output filter that escapes all HTML entities in the output
1928 function output_filter(r)
1929 coroutine.yield("(Handled by myOutputFilter)<br/>\n") -- Prepend some data to the output,
1930 -- yield and wait for buckets.
1931 while bucket do -- For each bucket, do...
1932 local output = r:escape_html(bucket) -- Escape all output
1933 coroutine.yield(output) -- Send converted data down the chain
1935 -- No more buckets available.
1939 As with the input filter, the output filter supports denying/skipping a filter
1940 if it is deemed unwanted:
1942 <highlight language="lua">
1943 function output_filter(r)
1944 if not r.content_type:match("text/html") then
1945 return -- Simply deny filtering, passing on the original content instead
1947 coroutine.yield() -- wait for buckets
1948 ... -- insert filter stuff here
1951 <note><title>Lua filters with <module>mod_filter</module></title>
1952 <p> When a Lua filter is used as the underlying provider via the
1953 <directive module="mod_filter">FilterProvider</directive> directive, filtering
1954 will only work when the <var>filter-name</var> is identical to the <var>provider-name</var>.
1958 See "<a href="#modifying_buckets">Modifying contents with Lua filters</a>" for more
1963 </directivesynopsis>