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 an <code>AddHandler</code> directive:</p>
71 <highlight language="config">
72 AddHandler lua-script .lua
76 This will cause <code>mod_lua</code> to handle requests for files
77 ending in <code>.lua</code> by invoking that file's
78 <code>handle</code> function.
81 <p>For more flexibility, see <directive>LuaMapHandler</directive>.
86 <section id="writinghandlers"><title>Writing Handlers</title>
87 <p> In the Apache HTTP Server API, the handler is a specific kind of hook
88 responsible for generating the response. Examples of modules that include a
89 handler are <module>mod_proxy</module>, <module>mod_cgi</module>,
90 and <module>mod_status</module>.</p>
92 <p><code>mod_lua</code> always looks to invoke a Lua function for the handler, rather than
93 just evaluating a script body CGI style. A handler function looks
94 something like this:</p>
97 <highlight language="lua">
98 <strong>example.lua</strong><br/>
104 This is the default method name for Lua handlers, see the optional
105 function-name in the LuaMapHandler directive to choose a different
109 r.content_type = "text/plain"
111 if r.method == 'GET' then
112 r:puts("Hello Lua World!\n")
113 for k, v in pairs( r:parseargs() ) do
114 r:puts( string.format("%s: %s\n", k, v) )
116 elseif r.method == 'POST' then
117 r:puts("Hello Lua World!\n")
118 for k, v in pairs( r:parsebody() ) do
119 r:puts( string.format("%s: %s\n", k, v) )
121 elseif r.method == 'PUT' then
122 -- use our own Error contents
123 r:puts("Unsupported HTTP method " .. r.method)
127 -- use the ErrorDocument
135 This handler function just prints out the uri or form encoded
136 arguments to a plaintext page.
140 This means (and in fact encourages) that you can have multiple
141 handlers (or hooks, or filters) in the same script.
146 <section id="writingauthzproviders">
147 <title>Writing Authorization Providers</title>
149 <p><module>mod_authz_core</module> provides a high-level interface to
150 authorization that is much easier to use than using into the relevant
151 hooks directly. The first argument to the
152 <directive module="mod_authz_core">Require</directive> directive gives
153 the name of the responsible authorization provider. For any
154 <directive module="mod_authz_core">Require</directive> line,
155 <module>mod_authz_core</module> will call the authorization provider
156 of the given name, passing the rest of the line as parameters. The
157 provider will then check authorization and pass the result as return
160 <p>The authz provider is normally called before authentication. If it needs to
161 know the authenticated user name (or if the user will be authenticated at
162 all), the provider must return <code>apache2.AUTHZ_DENIED_NO_USER</code>.
163 This will cause authentication to proceed and the authz provider to be
164 called a second time.</p>
166 <p>The following authz provider function takes two arguments, one ip
167 address and one user name. It will allow access from the given ip address
168 without authentication, or if the authenticated user matches the second
171 <highlight language="lua">
172 <strong>authz_provider.lua</strong><br/>
176 function authz_check_foo(r, ip, user)
177 if r.useragent_ip == ip then
178 return apache2.AUTHZ_GRANTED
179 elseif r.user == nil then
180 return apache2.AUTHZ_DENIED_NO_USER
181 elseif r.user == user then
182 return apache2.AUTHZ_GRANTED
184 return apache2.AUTHZ_DENIED
189 <p>The following configuration registers this function as provider
190 <code>foo</code> and configures it for URL <code>/</code>:</p>
191 <highlight language="config">
192 LuaAuthzProvider foo authz_provider.lua authz_check_foo
194 Require foo 10.1.2.3 john_doe
200 <section id="writinghooks"><title>Writing Hooks</title>
202 <p>Hook functions are how modules (and Lua scripts) participate in the
203 processing of requests. Each type of hook exposed by the server exists for
204 a specific purpose, such as mapping requests to the file system,
205 performing access control, or setting mime types:</p>
207 <table border="1" style="zebra">
210 <th>mod_lua directive</th>
214 <td>Quick handler</td>
215 <td><directive module="mod_lua">LuaQuickHandler</directive></td>
216 <td>This is the first hook that will be called after a request has
217 been mapped to a host or virtual host</td>
220 <td>Translate name</td>
221 <td><directive module="mod_lua">LuaHookTranslateName</directive></td>
222 <td>This phase translates the requested URI into a filename on the
223 system. Modules such as <module>mod_alias</module> and
224 <module>mod_rewrite</module> operate in this phase.</td>
227 <td>Map to storage</td>
228 <td><directive module="mod_lua">LuaHookMapToStorage</directive></td>
229 <td>This phase maps files to their physical, cached or external/proxied storage.
230 It can be used by proxy or caching modules</td>
233 <td>Check Access</td>
234 <td><directive module="mod_lua">LuaHookAccessChecker</directive></td>
235 <td>This phase checks whether a client has access to a resource. This
236 phase is run before the user is authenticated, so beware.
240 <td>Check User ID</td>
241 <td><directive module="mod_lua">LuaHookCheckUserID</directive></td>
242 <td>This phase it used to check the negotiated user ID</td>
245 <td>Check Authorization</td>
246 <td><directive module="mod_lua">LuaHookAuthChecker</directive> or
247 <directive module="mod_lua">LuaAuthzProvider</directive></td>
248 <td>This phase authorizes a user based on the negotiated credentials, such as
249 user ID, client certificate etc.
254 <td><directive module="mod_lua">LuaHookTypeChecker</directive></td>
255 <td>This phase checks the requested file and assigns a content type and
260 <td><directive module="mod_lua">LuaHookFixups</directive></td>
261 <td>This is the final "fix anything" phase before the content handlers
262 are run. Any last-minute changes to the request should be made here.</td>
265 <td>Content handler</td>
266 <td>fx. <code>.lua</code> files or through <directive module="mod_lua">LuaMapHandler</directive></td>
267 <td>This is where the content is handled. Files are read, parsed, some are run,
268 and the result is sent to the client</td>
273 <td>Once a request has been handled, it enters several logging phases,
274 which logs the request in either the error or access log</td>
279 <p>Hook functions are passed the request object as their only argument
280 (except for LuaAuthzProvider, which also gets passed the arguments from
281 the Require directive).
282 They can return any value, depending on the hook, but most commonly
283 they'll return OK, DONE, or DECLINED, which you can write in Lua as
284 <code>apache2.OK</code>, <code>apache2.DONE</code>, or
285 <code>apache2.DECLINED</code>, or else an HTTP status code.</p>
288 <highlight language="lua">
289 <strong>translate_name.lua</strong><br/>
290 -- example hook that rewrites the URI to a filesystem path.
294 function translate_name(r)
295 if r.uri == "/translate-name" then
296 r.filename = r.document_root .. "/find_me.txt"
299 -- we don't care about this URL, give another module a chance
300 return apache2.DECLINED
305 <highlight language="lua">
306 <strong>translate_name2.lua</strong><br/>
307 --[[ example hook that rewrites one URI to another URI. It returns a
308 apache2.DECLINED to give other URL mappers a chance to work on the
309 substitution, including the core translate_name hook which maps based
312 Note: Use the early/late flags in the directive to make it run before
318 function translate_name(r)
319 if r.uri == "/translate-name" then
320 r.uri = "/find_me.txt"
321 return apache2.DECLINED
323 return apache2.DECLINED
328 <section id="datastructures"><title>Data Structures</title>
333 <p>The request_rec is mapped in as a userdata. It has a metatable
334 which lets you do useful things with it. For the most part it
335 has the same fields as the request_rec struct, many of which are writable as
336 well as readable. (The table fields' content can be changed, but the
337 fields themselves cannot be set to different tables.)</p>
339 <table border="1" style="zebra">
342 <th><strong>Name</strong></th>
343 <th><strong>Lua type</strong></th>
344 <th><strong>Writable</strong></th>
345 <th><strong>Description</strong></th>
348 <td><code>allowoverrides</code></td>
351 <td>The AllowOverride options applied to the current request.</td>
354 <td><code>ap_auth_type</code></td>
357 <td>If an authentication check was made, this is set to the type
358 of authentication (f.x. <code>basic</code>)</td>
361 <td><code>args</code></td>
364 <td>The query string arguments extracted from the request
365 (f.x. <code>foo=bar&name=johnsmith</code>)</td>
368 <td><code>assbackwards</code></td>
371 <td>Set to true if this is an HTTP/0.9 style request
372 (e.g. <code>GET /foo</code> (with no headers) )</td>
375 <td><code>auth_name</code></td>
378 <td>The realm name used for authorization (if applicable).</td>
381 <td><code>banner</code></td>
384 <td>The server banner, f.x. <code>Apache HTTP Server/2.4.3 openssl/0.9.8c</code></td>
387 <td><code>basic_auth_pw</code></td>
390 <td>The basic auth password sent with this request, if any</td>
393 <td><code>canonical_filename</code></td>
396 <td>The canonical filename of the request</td>
399 <td><code>content_encoding</code></td>
402 <td>The content encoding of the current request</td>
405 <td><code>content_type</code></td>
408 <td>The content type of the current request, as determined in the
409 type_check phase (f.x. <code>image/gif</code> or <code>text/html</code>)</td>
412 <td><code>context_prefix</code></td>
418 <td><code>context_document_root</code></td>
425 <td><code>document_root</code></td>
428 <td>The document root of the host</td>
431 <td><code>err_headers_out</code></td>
434 <td>MIME header environment for the response, printed even on errors and
435 persist across internal redirects</td>
438 <td><code>filename</code></td>
441 <td>The file name that the request maps to, f.x. /www/example.com/foo.txt. This can be
442 changed in the translate-name or map-to-storage phases of a request to allow the
443 default handler (or script handlers) to serve a different file than what was requested.</td>
446 <td><code>handler</code></td>
449 <td>The name of the <a href="../handler.html">handler</a> that should serve this request, f.x.
450 <code>lua-script</code> if it is to be served by mod_lua. This is typically set by the
451 <directive module="mod_mime">AddHandler</directive> or <directive module="core">SetHandler</directive>
452 directives, but could also be set via mod_lua to allow another handler to serve up a specific request
453 that would otherwise not be served by it.
458 <td><code>headers_in</code></td>
461 <td>MIME header environment from the request. This contains headers such as <code>Host,
462 User-Agent, Referer</code> and so on.</td>
465 <td><code>headers_out</code></td>
468 <td>MIME header environment for the response.</td>
471 <td><code>hostname</code></td>
474 <td>The host name, as set by the <code>Host:</code> header or by a full URI.</td>
477 <td><code>is_https</code></td>
480 <td>Whether or not this request is done via HTTPS</td>
483 <td><code>is_initial_req</code></td>
486 <td>Whether this request is the initial request or a sub-request</td>
489 <td><code>limit_req_body</code></td>
492 <td>The size limit of the request body for this request, or 0 if no limit.</td>
495 <td><code>log_id</code></td>
498 <td>The ID to identify request in access and error log.</td>
501 <td><code>method</code></td>
504 <td>The request method, f.x. <code>GET</code> or <code>POST</code>.</td>
507 <td><code>notes</code></td>
510 <td>A list of notes that can be passed on from one module to another.</td>
513 <td><code>options</code></td>
516 <td>The Options directive applied to the current request.</td>
519 <td><code>path_info</code></td>
522 <td>The PATH_INFO extracted from this request.</td>
525 <td><code>port</code></td>
528 <td>The server port used by the request.</td>
531 <td><code>protocol</code></td>
534 <td>The protocol used, f.x. <code>HTTP/1.1</code></td>
537 <td><code>proxyreq</code></td>
540 <td>Denotes whether this is a proxy request or not. This value is generally set in
541 the post_read_request/translate_name phase of a request.</td>
544 <td><code>range</code></td>
547 <td>The contents of the <code>Range:</code> header.</td>
550 <td><code>remaining</code></td>
553 <td>The number of bytes remaining to be read from the request body.</td>
556 <td><code>server_built</code></td>
559 <td>The time the server executable was built.</td>
562 <td><code>server_name</code></td>
565 <td>The server name for this request.</td>
568 <td><code>some_auth_required</code></td>
571 <td>Whether some authorization is/was required for this request.</td>
574 <td><code>subprocess_env</code></td>
577 <td>The environment variables set for this request.</td>
580 <td><code>started</code></td>
583 <td>The time the server was (re)started, in seconds since the epoch (Jan 1st, 1970)</td>
586 <td><code>status</code></td>
589 <td>The (current) HTTP return code for this request, f.x. <code>200</code> or <code>404</code>.</td>
592 <td><code>the_request</code></td>
595 <td>The request string as sent by the client, f.x. <code>GET /foo/bar HTTP/1.1</code>.</td>
598 <td><code>unparsed_uri</code></td>
601 <td>The unparsed URI of the request</td>
604 <td><code>uri</code></td>
607 <td>The URI after it has been parsed by httpd</td>
610 <td><code>user</code></td>
613 <td>If an authentication check has been made, this is set to the name of the authenticated user.</td>
616 <td><code>useragent_ip</code></td>
619 <td>The IP of the user agent making the request</td>
625 <section id="functions"><title>Built in functions</title>
627 <p>The request_rec object has (at least) the following methods:</p>
629 <highlight language="lua">
630 r:flush() -- flushes the output buffer.
631 -- Returns true if the flush was successful, false otherwise.
633 while we_have_stuff_to_send do
634 r:puts("Bla bla bla\n") -- print something to client
635 r:flush() -- flush the buffer (send to client)
636 r.usleep(500000) -- fake processing time for 0.5 sec. and repeat
640 <highlight language="lua">
641 r:addoutputfilter(name|function) -- add an output filter:
643 r:addoutputfilter("fooFilter") -- add the fooFilter to the output stream
646 <highlight language="lua">
647 r:sendfile(filename) -- sends an entire file to the client, using sendfile if supported by the current platform:
649 if use_sendfile_thing then
650 r:sendfile("/var/www/large_file.img")
654 <highlight language="lua">
655 r:parseargs() -- returns two tables; one standard key/value table for regular GET data,
656 -- and one for multi-value data (fx. foo=1&foo=2&foo=3):
658 local GET, GETMULTI = r:parseargs()
659 r:puts("Your name is: " .. GET['name'] or "Unknown")
662 <highlight language="lua">
663 r:parsebody([sizeLimit]) -- parse the request body as a POST and return two lua tables,
664 -- just like r:parseargs().
665 -- An optional number may be passed to specify the maximum number
666 -- of bytes to parse. Default is 8192 bytes:
668 local POST, POSTMULTI = r:parsebody(1024*1024)
669 r:puts("Your name is: " .. POST['name'] or "Unknown")
672 <highlight language="lua">
673 r:puts("hello", " world", "!") -- print to response body, self explanatory
676 <highlight language="lua">
677 r:write("a single string") -- print to response body, self explanatory
680 <highlight language="lua">
681 r:escape_html("<html>test</html>") -- Escapes HTML code and returns the escaped result
684 <highlight language="lua">
685 r:base64_encode(string) -- Encodes a string using the Base64 encoding standard:
687 local encoded = r:base64_encode("This is a test") -- returns VGhpcyBpcyBhIHRlc3Q=
690 <highlight language="lua">
691 r:base64_decode(string) -- Decodes a Base64-encoded string:
693 local decoded = r:base64_decode("VGhpcyBpcyBhIHRlc3Q=") -- returns 'This is a test'
696 <highlight language="lua">
697 r:md5(string) -- Calculates and returns the MD5 digest of a string (binary safe):
699 local hash = r:md5("This is a test") -- returns ce114e4501d2f4e2dcea3e17b546f339
702 <highlight language="lua">
703 r:sha1(string) -- Calculates and returns the SHA1 digest of a string (binary safe):
705 local hash = r:sha1("This is a test") -- returns a54d88e06612d820bc3be72877c74f257b561b19
708 <highlight language="lua">
709 r:escape(string) -- URL-Escapes a string:
711 local url = "http://foo.bar/1 2 3 & 4 + 5"
712 local escaped = r:escape(url) -- returns 'http%3a%2f%2ffoo.bar%2f1+2+3+%26+4+%2b+5'
715 <highlight language="lua">
716 r:unescape(string) -- Unescapes an URL-escaped string:
718 local url = "http%3a%2f%2ffoo.bar%2f1+2+3+%26+4+%2b+5"
719 local unescaped = r:unescape(url) -- returns 'http://foo.bar/1 2 3 & 4 + 5'
722 <highlight language="lua">
723 r:construct_url(string) -- Constructs an URL from an URI
725 local url = r:construct_url(r.uri)
728 <highlight language="lua">
729 r.mpm_query(number) -- Queries the server for MPM information using ap_mpm_query:
731 local mpm = r.mpm_query(14)
733 r:puts("This server uses the Event MPM")
737 <highlight language="lua">
738 r:expr(string) -- Evaluates an <a href="../expr.html">expr</a> string.
740 if r:expr("%{HTTP_HOST} =~ /^www/") then
741 r:puts("This host name starts with www")
745 <highlight language="lua">
746 r:scoreboard_process(a) -- Queries the server for information about the process at position <code>a</code>:
748 local process = r:scoreboard_process(1)
749 r:puts("Server 1 has PID " .. process.pid)
752 <highlight language="lua">
753 r:scoreboard_worker(a, b) -- Queries for information about the worker thread, <code>b</code>, in process <code>a</code>:
755 local thread = r:scoreboard_worker(1, 1)
756 r:puts("Server 1's thread 1 has thread ID " .. thread.tid .. " and is in " .. thread.status .. " status")
760 <highlight language="lua">
761 r:clock() -- Returns the current time with microsecond precision
764 <highlight language="lua">
765 r:requestbody(filename) -- Reads and returns the request body of a request.
766 -- If 'filename' is specified, it instead saves the
767 -- contents to that file:
769 local input = r:requestbody()
770 r:puts("You sent the following request body to me:\n")
774 <highlight language="lua">
775 r:add_input_filter(filter_name) -- Adds 'filter_name' as an input filter
778 <highlight language="lua">
779 r.module_info(module_name) -- Queries the server for information about a module
781 local mod = r.module_info("mod_lua.c")
783 for k, v in pairs(mod.commands) do
784 r:puts( ("%s: %s\n"):format(k,v)) -- print out all directives accepted by this module
789 <highlight language="lua">
790 r:loaded_modules() -- Returns a list of modules loaded by httpd:
792 for k, module in pairs(r:loaded_modules()) do
793 r:puts("I have loaded module " .. module .. "\n")
797 <highlight language="lua">
798 r:runtime_dir_relative(filename) -- Compute the name of a run-time file (e.g., shared memory "file")
799 -- relative to the appropriate run-time directory.
802 <highlight language="lua">
803 r:server_info() -- Returns a table containing server information, such as
804 -- the name of the httpd executable file, mpm used etc.
807 <highlight language="lua">
808 r:set_document_root(file_path) -- Sets the document root for the request to file_path
812 <highlight language="lua">
813 r:add_version_component(component_string) - - Adds a component to the server banner.
817 <highlight language="lua">
818 r:set_context_info(prefix, docroot) -- Sets the context prefix and context document root for a request
821 <highlight language="lua">
822 r:os_escape_path(file_path) -- Converts an OS path to a URL in an OS dependent way
825 <highlight language="lua">
826 r:escape_logitem(string) -- Escapes a string for logging
829 <highlight language="lua">
830 r.strcmp_match(string, pattern) -- Checks if 'string' matches 'pattern' using strcmp_match (globs).
831 -- fx. whether 'www.example.com' matches '*.example.com':
833 local match = r.strcmp_match("foobar.com", "foo*.com")
835 r:puts("foobar.com matches foo*.com")
839 <highlight language="lua">
840 r:set_keepalive() -- Sets the keepalive status for a request. Returns true if possible, false otherwise.
843 <highlight language="lua">
844 r:make_etag() -- Constructs and returns the etag for the current request.
847 <highlight language="lua">
848 r:send_interim_response(clear) -- Sends an interim (1xx) response to the client.
849 -- if 'clear' is true, available headers will be sent and cleared.
852 <highlight language="lua">
853 r:custom_response(status_code, string) -- Construct and set a custom response for a given status code.
854 -- This works much like the ErrorDocument directive:
856 r:custom_response(404, "Baleted!")
859 <highlight language="lua">
860 r.exists_config_define(string) -- Checks whether a configuration definition exists or not:
862 if r.exists_config_define("FOO") then
863 r:puts("httpd was probably run with -DFOO, or it was defined in the configuration")
867 <highlight language="lua">
868 r:state_query(string) -- Queries the server for state information
871 <highlight language="lua">
872 r:stat(filename [,wanted]) -- Runs stat() on a file, and returns a table with file information:
874 local info = r:stat("/var/www/foo.txt")
876 r:puts("This file exists and was last modified at: " .. info.modified)
880 <highlight language="lua">
881 r:regex(string, pattern [,flags]) -- Runs a regular expression match on a string, returning captures if matched:
883 local matches = r:regex("foo bar baz", [[foo (\w+) (\S*)]])
885 r:puts("The regex matched, and the last word captured ($2) was: " .. matches[2])
888 -- Example ignoring case sensitivity:
889 local matches = r:regex("FOO bar BAz", [[(foo) bar]], 1)
891 -- Flags can be a bitwise combination of:
893 -- 0x02: Multiline search
896 <highlight language="lua">
897 r.usleep(number_of_microseconds) -- Puts the script to sleep for a given number of microseconds.
900 <highlight language="lua">
901 r:dbacquire(dbType[, dbParams]) -- Acquires a connection to a database and returns a database class.
902 -- See '<a href="#databases">Database connectivity</a>' for details.
905 <highlight language="lua">
906 r:ivm_set("key", value) -- Set an Inter-VM variable to hold a specific value.
907 -- These values persist even though the VM is gone or not being used,
908 -- and so should only be used if MaxConnectionsPerChild is > 0
909 -- Values can be numbers, strings and booleans, and are stored on a
910 -- per process basis (so they won't do much good with a prefork mpm)
912 r:ivm_get("key") -- Fetches a variable set by ivm_set. Returns the contents of the variable
913 -- if it exists or nil if no such variable exists.
915 -- An example getter/setter that saves a global variable outside the VM:
917 -- First VM to call this will get no value, and will have to create it
918 local foo = r:ivm_get("cached_data")
920 foo = do_some_calcs() -- fake some return value
921 r:ivm_set("cached_data", foo) -- set it globally
923 r:puts("Cached data is: ", foo)
927 <highlight language="lua">
928 r:htpassword(string [,algorithm [,cost]]) -- Creates a password hash from a string.
929 -- algorithm: 0 = APMD5 (default), 1 = SHA, 2 = BCRYPT, 3 = CRYPT.
930 -- cost: only valid with BCRYPT algorithm (default = 5).
933 <highlight language="lua">
934 r:mkdir(dir [,mode]) -- Creates a directory and sets mode to optional mode paramter.
937 <highlight language="lua">
938 r:mkrdir(dir [,mode]) -- Creates directories recursive and sets mode to optional mode paramter.
941 <highlight language="lua">
942 r:rmdir(dir) -- Removes a directory.
945 <highlight language="lua">
946 r:touch([mtime]) -- Sets the file modification time to current time or to optional mtime msec value.
949 <highlight language="lua">
950 r:get_direntries(dir) -- Returns a table with all directory entries.
953 local dir = r.context_document_root
954 for _, f in ipairs(r:get_direntries(dir)) do
955 local info = r:stat(dir .. "/" .. f)
957 local mtime = os.date(fmt, info.mtime / 1000000)
958 local ftype = (info.filetype == 2) and "[dir] " or "[file]"
959 r:puts( ("%s %s %10i %s\n"):format(ftype, mtime, info.size, f) )
965 <highlight language="lua">
966 r.date_parse_rfc(string) -- Parses a date/time string and returns seconds since epoche.
971 <section id="logging"><title>Logging Functions</title>
973 <highlight language="lua">
974 -- examples of logging messages<br />
975 r:trace1("This is a trace log message") -- trace1 through trace8 can be used <br />
976 r:debug("This is a debug log message")<br />
977 r:info("This is an info log message")<br />
978 r:notice("This is a notice log message")<br />
979 r:warn("This is a warn log message")<br />
980 r:err("This is an err log message")<br />
981 r:alert("This is an alert log message")<br />
982 r:crit("This is a crit log message")<br />
983 r:emerg("This is an emerg log message")<br />
988 <section id="apache2"><title>apache2 Package</title>
989 <p>A package named <code>apache2</code> is available with (at least) the following contents.</p>
992 <dd>internal constant OK. Handlers should return this if they've
993 handled the request.</dd>
994 <dt>apache2.DECLINED</dt>
995 <dd>internal constant DECLINED. Handlers should return this if
996 they are not going to handle the request.</dd>
997 <dt>apache2.DONE</dt>
998 <dd>internal constant DONE.</dd>
999 <dt>apache2.version</dt>
1000 <dd>Apache HTTP server version string</dd>
1001 <dt>apache2.HTTP_MOVED_TEMPORARILY</dt>
1002 <dd>HTTP status code</dd>
1003 <dt>apache2.PROXYREQ_NONE, apache2.PROXYREQ_PROXY, apache2.PROXYREQ_REVERSE, apache2.PROXYREQ_RESPONSE</dt>
1004 <dd>internal constants used by <module>mod_proxy</module></dd>
1005 <dt>apache2.AUTHZ_DENIED, apache2.AUTHZ_GRANTED, apache2.AUTHZ_NEUTRAL, apache2.AUTHZ_GENERAL_ERROR, apache2.AUTHZ_DENIED_NO_USER</dt>
1006 <dd>internal constants used by <module>mod_authz_core</module></dd>
1009 <p>(Other HTTP status codes are not yet implemented.)</p>
1012 <section id="modifying_buckets">
1013 <title>Modifying contents with Lua filters</title>
1015 Filter functions implemented via <directive module="mod_lua">LuaInputFilter</directive>
1016 or <directive module="mod_lua">LuaOutputFilter</directive> are designed as
1017 three-stage non-blocking functions using coroutines to suspend and resume a
1018 function as buckets are sent down the filter chain. The core structure of
1021 <highlight language="lua">
1023 -- Our first yield is to signal that we are ready to receive buckets.
1024 -- Before this yield, we can set up our environment, check for conditions,
1025 -- and, if we deem it necessary, decline filtering a request alltogether:
1026 if something_bad then
1027 return -- This would skip this filter.
1029 -- Regardless of whether we have data to prepend, a yield MUST be called here.
1030 -- Note that only output filters can prepend data. Input filters must use the
1031 -- final stage to append data to the content.
1032 coroutine.yield([optional header to be prepended to the content])
1034 -- After we have yielded, buckets will be sent to us, one by one, and we can
1035 -- do whatever we want with them and then pass on the result.
1036 -- Buckets are stored in the global variable 'bucket', so we create a loop
1037 -- that checks if 'bucket' is not nil:
1038 while bucket ~= nil do
1039 local output = mangle(bucket) -- Do some stuff to the content
1040 coroutine.yield(output) -- Return our new content to the filter chain
1043 -- Once the buckets are gone, 'bucket' is set to nil, which will exit the
1044 -- loop and land us here. Anything extra we want to append to the content
1045 -- can be done by doing a final yield here. Both input and output filters
1046 -- can append data to the content in this phase.
1047 coroutine.yield([optional footer to be appended to the content])
1052 <section id="databases">
1053 <title>Database connectivity</title>
1055 Mod_lua implements a simple database feature for querying and running commands
1056 on the most popular database engines (mySQL, PostgreSQL, FreeTDS, ODBC, SQLite, Oracle)
1059 <p>The example below shows how to acquire a database handle and return information from a table:</p>
1060 <highlight language="lua">
1062 -- Acquire a database handle
1063 local database, err = r:dbacquire("mysql", "server=localhost,user=root,dbname=mydb")
1065 -- Select some information from it
1066 local results, err = database:select(r, "SELECT `name`, `age` FROM `people` WHERE 1")
1068 local rows = results(0) -- fetch all rows synchronously
1069 for k, row in pairs(rows) do
1070 r:puts( string.format("Name: %s, Age: %s<br/>", row[1], row[2]) )
1073 r:puts("Database query error: " .. err)
1077 r:puts("Could not connect to the database: " .. err)
1082 To utilize <module>mod_dbd</module>, specify <code>mod_dbd</code>
1083 as the database type, or leave the field blank:
1085 <highlight language="lua">
1086 local database = r:dbacquire("mod_dbd")
1088 <section id="database_object">
1089 <title>Database object and contained functions</title>
1090 <p>The database object returned by <code>dbacquire</code> has the following methods:</p>
1091 <p><strong>Normal select and query from a database:</strong></p>
1092 <highlight language="lua">
1093 -- Run a statement and return the number of rows affected:
1094 local affected, errmsg = database:query(r, "DELETE FROM `tbl` WHERE 1")
1096 -- Run a statement and return a result set that can be used synchronously or async:
1097 local result, errmsg = database:select(r, "SELECT * FROM `people` WHERE 1")
1099 <p><strong>Using prepared statements (recommended):</strong></p>
1100 <highlight language="lua">
1101 -- Create and run a prepared statement:
1102 local statement, errmsg = database:prepare(r, "DELETE FROM `tbl` WHERE `age` > %u")
1104 local result, errmsg = statement:query(20) -- run the statement with age > 20
1107 -- Fetch a prepared statement from a DBDPrepareSQL directive:
1108 local statement, errmsg = database:prepared(r, "someTag")
1110 local result, errmsg = statement:select("John Doe", 123) -- inject the values "John Doe" and 123 into the statement
1114 <p><strong>Escaping values, closing databases etc:</strong></p>
1115 <highlight language="lua">
1116 -- Escape a value for use in a statement:
1117 local escaped = database:escape(r, [["'|blabla]])
1119 -- Close a database connection and free up handles:
1122 -- Check whether a database connection is up and running:
1123 local connected = database:active()
1126 <section id="result_sets">
1127 <title>Working with result sets</title>
1128 <p>The result set returned by <code>db:select</code> or by the prepared statement functions
1129 created through <code>db:prepare</code> can be used to
1130 fetch rows synchronously or asynchronously, depending on the row number specified:<br/>
1131 <code>result(0)</code> fetches all rows in a synchronous manner, returning a table of rows.<br/>
1132 <code>result(-1)</code> fetches the next available row in the set, asynchronously.<br/>
1133 <code>result(N)</code> fetches row number <code>N</code>, asynchronously:
1135 <highlight language="lua">
1136 -- fetch a result set using a regular query:
1137 local result, err = db:select(r, "SELECT * FROM `tbl` WHERE 1")
1139 local rows = result(0) -- Fetch ALL rows synchronously
1140 local row = result(-1) -- Fetch the next available row, asynchronously
1141 local row = result(1234) -- Fetch row number 1234, asynchronously
1143 <p>One can construct a function that returns an iterative function to iterate over all rows
1144 in a synchronous or asynchronous way, depending on the async argument:
1146 <highlight language="lua">
1147 function rows(resultset, async)
1149 local function getnext()
1151 local row = resultset(-1)
1152 return row and a or nil, row
1155 return pairs(resultset(0))
1157 return getnext, self
1161 local statement, err = db:prepare(r, "SELECT * FROM `tbl` WHERE `age` > %u")
1163 -- fetch rows asynchronously:
1164 local result, err = statement:select(20)
1166 for index, row in rows(result, true) do
1171 -- fetch rows synchronously:
1172 local result, err = statement:select(20)
1174 for index, row in rows(result, false) do
1181 <section id="closing_databases">
1182 <title>Closing a database connection</title>
1184 <p>Database handles should be closed using <code>database:close()</code> when they are no longer
1185 needed. If you do not close them manually, they will eventually be garbage collected and
1186 closed by mod_lua, but you may end up having too many unused connections to the database
1187 if you leave the closing up to mod_lua. Essentially, the following two measures are
1190 <highlight language="lua">
1191 -- Method 1: Manually close a handle
1192 local database = r:dbacquire("mod_dbd")
1193 database:close() -- All done
1195 -- Method 2: Letting the garbage collector close it
1196 local database = r:dbacquire("mod_dbd")
1197 database = nil -- throw away the reference
1198 collectgarbage() -- close the handle via GC
1201 <section id="database_caveat">
1202 <title>Precautions when working with databases</title>
1203 <p>Although the standard <code>query</code> and <code>run</code> functions are freely
1204 available, it is recommended that you use prepared statements whenever possible, to
1205 both optimize performance (if your db handle lives on for a long time) and to minimize
1206 the risk of SQL injection attacks. <code>run</code> and <code>query</code> should only
1207 be used when there are no variables inserted into a statement (a static statement).
1208 When using dynamic statements, use <code>db:prepare</code> or <code>db:prepared</code>.
1215 <name>LuaRoot</name>
1216 <description>Specify the base path for resolving relative paths for mod_lua directives</description>
1217 <syntax>LuaRoot /path/to/a/directory</syntax>
1218 <contextlist><context>server config</context><context>virtual host</context>
1219 <context>directory</context><context>.htaccess</context>
1221 <override>All</override>
1224 <p>Specify the base path which will be used to evaluate all
1225 relative paths within mod_lua. If not specified they
1226 will be resolved relative to the current working directory,
1227 which may not always work well for a server.</p>
1229 </directivesynopsis>
1232 <name>LuaScope</name>
1233 <description>One of once, request, conn, thread -- default is once</description>
1234 <syntax>LuaScope once|request|conn|thread|server [min] [max]</syntax>
1235 <default>LuaScope once</default>
1236 <contextlist><context>server config</context><context>virtual host</context>
1237 <context>directory</context><context>.htaccess</context>
1239 <override>All</override>
1242 <p>Specify the life cycle scope of the Lua interpreter which will
1243 be used by handlers in this "Directory." The default is "once"</p>
1246 <dt>once:</dt> <dd>use the interpreter once and throw it away.</dd>
1248 <dt>request:</dt> <dd>use the interpreter to handle anything based on
1249 the same file within this request, which is also
1250 request scoped.</dd>
1252 <dt>conn:</dt> <dd>Same as request but attached to the connection_rec</dd>
1254 <dt>thread:</dt> <dd>Use the interpreter for the lifetime of the thread
1255 handling the request (only available with threaded MPMs).</dd>
1257 <dt>server:</dt> <dd>This one is different than others because the
1258 server scope is quite long lived, and multiple threads
1259 will have the same server_rec. To accommodate this,
1260 server scoped Lua states are stored in an apr
1261 resource list. The <code>min</code> and <code>max</code> arguments
1262 specify the minimum and maximum number of Lua states to keep in the
1266 Generally speaking, the <code>thread</code> and <code>server</code> scopes
1267 execute roughly 2-3 times faster than the rest, because they don't have to
1268 spawn new Lua states on every request (especially with the event MPM, as
1269 even keepalive requests will use a new thread for each request). If you are
1270 satisfied that your scripts will not have problems reusing a state, then
1271 the <code>thread</code> or <code>server</code> scopes should be used for
1272 maximum performance. While the <code>thread</code> scope will provide the
1273 fastest responses, the <code>server</code> scope will use less memory, as
1274 states are pooled, allowing f.x. 1000 threads to share only 100 Lua states,
1275 thus using only 10% of the memory required by the <code>thread</code> scope.
1278 </directivesynopsis>
1281 <name>LuaMapHandler</name>
1282 <description>Map a path to a lua handler</description>
1283 <syntax>LuaMapHandler uri-pattern /path/to/lua/script.lua [function-name]</syntax>
1284 <contextlist><context>server config</context><context>virtual host</context>
1285 <context>directory</context><context>.htaccess</context>
1287 <override>All</override>
1289 <p>This directive matches a uri pattern to invoke a specific
1290 handler function in a specific file. It uses PCRE regular
1291 expressions to match the uri, and supports interpolating
1292 match groups into both the file path and the function name.
1293 Be careful writing your regular expressions to avoid security
1295 <example><title>Examples:</title>
1296 <highlight language="config">
1297 LuaMapHandler /(\w+)/(\w+) /scripts/$1.lua handle_$2
1300 <p>This would match uri's such as /photos/show?id=9
1301 to the file /scripts/photos.lua and invoke the
1302 handler function handle_show on the lua vm after
1303 loading that file.</p>
1305 <highlight language="config">
1306 LuaMapHandler /bingo /scripts/wombat.lua
1308 <p>This would invoke the "handle" function, which
1309 is the default if no specific function name is
1312 </directivesynopsis>
1315 <name>LuaPackagePath</name>
1316 <description>Add a directory to lua's package.path</description>
1317 <syntax>LuaPackagePath /path/to/include/?.lua</syntax>
1318 <contextlist><context>server config</context><context>virtual host</context>
1319 <context>directory</context><context>.htaccess</context>
1321 <override>All</override>
1322 <usage><p>Add a path to lua's module search path. Follows the same
1323 conventions as lua. This just munges the package.path in the
1326 <example><title>Examples:</title>
1327 <highlight language="config">
1328 LuaPackagePath /scripts/lib/?.lua
1329 LuaPackagePath /scripts/lib/?/init.lua
1333 </directivesynopsis>
1336 <name>LuaPackageCPath</name>
1337 <description>Add a directory to lua's package.cpath</description>
1338 <syntax>LuaPackageCPath /path/to/include/?.soa</syntax>
1339 <contextlist><context>server config</context><context>virtual host</context>
1340 <context>directory</context><context>.htaccess</context>
1342 <override>All</override>
1345 <p>Add a path to lua's shared library search path. Follows the same
1346 conventions as lua. This just munges the package.cpath in the
1350 </directivesynopsis>
1353 <name>LuaCodeCache</name>
1354 <description>Configure the compiled code cache.</description>
1355 <syntax>LuaCodeCache stat|forever|never</syntax>
1356 <default>LuaCodeCache stat</default>
1358 <context>server config</context><context>virtual host</context>
1359 <context>directory</context><context>.htaccess</context>
1361 <override>All</override>
1364 Specify the behavior of the in-memory code cache. The default
1365 is stat, which stats the top level script (not any included
1366 ones) each time that file is needed, and reloads it if the
1367 modified time indicates it is newer than the one it has
1368 already loaded. The other values cause it to keep the file
1369 cached forever (don't stat and replace) or to never cache the
1372 <p>In general stat or forever is good for production, and stat or never
1373 for development.</p>
1375 <example><title>Examples:</title>
1376 <highlight language="config">
1378 LuaCodeCache forever
1384 </directivesynopsis>
1387 <name>LuaHookTranslateName</name>
1388 <description>Provide a hook for the translate name phase of request processing</description>
1389 <syntax>LuaHookTranslateName /path/to/lua/script.lua hook_function_name [early|late]</syntax>
1390 <contextlist><context>server config</context><context>virtual host</context>
1392 <override>All</override>
1393 <compatibility>The optional third argument is supported in 2.3.15 and later</compatibility>
1396 Add a hook (at APR_HOOK_MIDDLE) to the translate name phase of
1397 request processing. The hook function receives a single
1398 argument, the request_rec, and should return a status code,
1399 which is either an HTTP error code, or the constants defined
1400 in the apache2 module: apache2.OK, apache2.DECLINED, or
1403 <p>For those new to hooks, basically each hook will be invoked
1404 until one of them returns apache2.OK. If your hook doesn't
1405 want to do the translation it should just return
1406 apache2.DECLINED. If the request should stop processing, then
1407 return apache2.DONE.</p>
1411 <highlight language="config">
1413 LuaHookTranslateName /scripts/conf/hooks.lua silly_mapper
1416 <highlight language="lua">
1417 -- /scripts/conf/hooks.lua --
1419 function silly_mapper(r)
1420 if r.uri == "/" then
1421 r.filename = "/var/www/home.lua"
1424 return apache2.DECLINED
1429 <note><title>Context</title><p>This directive is not valid in <directive
1430 type="section" module="core">Directory</directive>, <directive
1431 type="section" module="core">Files</directive>, or htaccess
1434 <note><title>Ordering</title><p>The optional arguments "early" or "late"
1435 control when this script runs relative to other modules.</p></note>
1438 </directivesynopsis>
1441 <name>LuaHookFixups</name>
1442 <description>Provide a hook for the fixups phase of a request
1443 processing</description>
1444 <syntax>LuaHookFixups /path/to/lua/script.lua hook_function_name</syntax>
1445 <contextlist><context>server config</context><context>virtual host</context>
1446 <context>directory</context><context>.htaccess</context>
1448 <override>All</override>
1451 Just like LuaHookTranslateName, but executed at the fixups phase
1454 </directivesynopsis>
1457 <name>LuaHookMapToStorage</name>
1458 <description>Provide a hook for the map_to_storage phase of request processing</description>
1459 <syntax>LuaHookMapToStorage /path/to/lua/script.lua hook_function_name</syntax>
1460 <contextlist><context>server config</context><context>virtual host</context>
1461 <context>directory</context><context>.htaccess</context>
1463 <override>All</override>
1465 <p>Like <directive>LuaHookTranslateName</directive> but executed at the
1466 map-to-storage phase of a request. Modules like mod_cache run at this phase,
1467 which makes for an interesting example on what to do here:</p>
1468 <highlight language="config">
1469 LuaHookMapToStorage /path/to/lua/script.lua check_cache
1471 <highlight language="lua">
1475 function read_file(filename)
1476 local input = io.open(filename, "r")
1478 local data = input:read("*a")
1479 cached_files[filename] = data
1480 file = cached_files[filename]
1483 return cached_files[filename]
1486 function check_cache(r)
1487 if r.filename:match("%.png$") then -- Only match PNG files
1488 local file = cached_files[r.filename] -- Check cache entries
1490 file = read_file(r.filename) -- Read file into cache
1492 if file then -- If file exists, write it out
1495 r:info(("Sent %s to client from cache"):format(r.filename))
1496 return apache2.DONE -- skip default handler for PNG files
1499 return apache2.DECLINED -- If we had nothing to do, let others serve this.
1504 </directivesynopsis>
1507 <name>LuaHookCheckUserID</name>
1508 <description>Provide a hook for the check_user_id phase of request processing</description>
1509 <syntax>LuaHookCheckUserID /path/to/lua/script.lua hook_function_name [early|late]</syntax>
1510 <contextlist><context>server config</context><context>virtual host</context>
1511 <context>directory</context><context>.htaccess</context>
1513 <override>All</override>
1514 <compatibility>The optional third argument is supported in 2.3.15 and later</compatibility>
1516 <note><title>Ordering</title><p>The optional arguments "early" or "late"
1517 control when this script runs relative to other modules.</p></note>
1519 </directivesynopsis>
1522 <name>LuaHookTypeChecker</name>
1523 <description>Provide a hook for the type_checker phase of request processing</description>
1524 <syntax>LuaHookTypeChecker /path/to/lua/script.lua hook_function_name</syntax>
1525 <contextlist><context>server config</context><context>virtual host</context>
1526 <context>directory</context><context>.htaccess</context>
1528 <override>All</override>
1530 This directive provides a hook for the type_checker phase of the request processing.
1531 This phase is where requests are assigned a content type and a handler, and thus can
1532 be used to modify the type and handler based on input:
1534 <highlight language="config">
1535 LuaHookTypeChecker /path/to/lua/script.lua type_checker
1537 <highlight language="lua">
1538 function type_checker(r)
1539 if r.uri:match("%.to_gif$") then -- match foo.png.to_gif
1540 r.content_type = "image/gif" -- assign it the image/gif type
1541 r.handler = "gifWizard" -- tell the gifWizard module to handle this
1542 r.filename = r.uri:gsub("%.to_gif$", "") -- fix the filename requested
1546 return apache2.DECLINED
1550 </directivesynopsis>
1553 <name>LuaHookAuthChecker</name>
1554 <description>Provide a hook for the auth_checker phase of request processing</description>
1555 <syntax>LuaHookAuthChecker /path/to/lua/script.lua hook_function_name [early|late]</syntax>
1556 <contextlist><context>server config</context><context>virtual host</context>
1557 <context>directory</context><context>.htaccess</context>
1559 <override>All</override>
1560 <compatibility>The optional third argument is supported in 2.3.15 and later</compatibility>
1562 <p>Invoke a lua function in the auth_checker phase of processing
1563 a request. This can be used to implement arbitrary authentication
1564 and authorization checking. A very simple example:
1566 <highlight language="lua">
1569 -- fake authcheck hook
1570 -- If request has no auth info, set the response header and
1571 -- return a 401 to ask the browser for basic auth info.
1572 -- If request has auth info, don't actually look at it, just
1573 -- pretend we got userid 'foo' and validated it.
1574 -- Then check if the userid is 'foo' and accept the request.
1575 function authcheck_hook(r)
1577 -- look for auth info
1578 auth = r.headers_in['Authorization']
1584 if r.user == nil then
1585 r:debug("authcheck: user is nil, returning 401")
1586 r.err_headers_out['WWW-Authenticate'] = 'Basic realm="WallyWorld"'
1588 elseif r.user == "foo" then
1589 r:debug('user foo: OK')
1591 r:debug("authcheck: user='" .. r.user .. "'")
1592 r.err_headers_out['WWW-Authenticate'] = 'Basic realm="WallyWorld"'
1598 <note><title>Ordering</title><p>The optional arguments "early" or "late"
1599 control when this script runs relative to other modules.</p></note>
1601 </directivesynopsis>
1604 <name>LuaHookAccessChecker</name>
1605 <description>Provide a hook for the access_checker phase of request processing</description>
1606 <syntax>LuaHookAccessChecker /path/to/lua/script.lua hook_function_name [early|late]</syntax>
1607 <contextlist><context>server config</context><context>virtual host</context>
1608 <context>directory</context><context>.htaccess</context>
1610 <override>All</override>
1611 <compatibility>The optional third argument is supported in 2.3.15 and later</compatibility>
1613 <p>Add your hook to the access_checker phase. An access checker
1614 hook function usually returns OK, DECLINED, or HTTP_FORBIDDEN.</p>
1615 <note><title>Ordering</title><p>The optional arguments "early" or "late"
1616 control when this script runs relative to other modules.</p></note>
1618 </directivesynopsis>
1621 <name>LuaHookInsertFilter</name>
1622 <description>Provide a hook for the insert_filter phase of request processing</description>
1623 <syntax>LuaHookInsertFilter /path/to/lua/script.lua hook_function_name</syntax>
1624 <contextlist><context>server config</context><context>virtual host</context>
1625 <context>directory</context><context>.htaccess</context>
1627 <override>All</override>
1628 <usage><p>Not Yet Implemented</p></usage>
1629 </directivesynopsis>
1632 <name>LuaInherit</name>
1633 <description>Controls how parent configuration sections are merged into children</description>
1634 <syntax>LuaInherit none|parent-first|parent-last</syntax>
1635 <default>LuaInherit parent-first</default>
1636 <contextlist><context>server config</context><context>virtual host</context>
1637 <context>directory</context><context>.htaccess</context>
1639 <override>All</override>
1640 <compatibility>2.4.0 and later</compatibility>
1641 <usage><p>By default, if LuaHook* directives are used in overlapping
1642 Directory or Location configuration sections, the scripts defined in the
1643 more specific section are run <em>after</em> those defined in the more
1644 generic section (LuaInherit parent-first). You can reverse this order, or
1645 make the parent context not apply at all.</p>
1647 <p> In previous 2.3.x releases, the default was effectively to ignore LuaHook*
1648 directives from parent configuration sections.</p></usage>
1649 </directivesynopsis>
1652 <name>LuaQuickHandler</name>
1653 <description>Provide a hook for the quick handler of request processing</description>
1654 <syntax>LuaQuickHandler /path/to/script.lua hook_function_name</syntax>
1655 <contextlist><context>server config</context><context>virtual host</context>
1657 <override>All</override>
1660 This phase is run immediately after the request has been mapped to a virtal host,
1661 and can be used to either do some request processing before the other phases kick
1662 in, or to serve a request without the need to translate, map to storage et cetera.
1663 As this phase is run before anything else, directives such as <directive
1664 type="section" module="core">Location</directive> or <directive
1665 type="section" module="core">Directory</directive> are void in this phase, just as
1666 URIs have not been properly parsed yet.
1668 <note><title>Context</title><p>This directive is not valid in <directive
1669 type="section" module="core">Directory</directive>, <directive
1670 type="section" module="core">Files</directive>, or htaccess
1673 </directivesynopsis>
1676 <name>LuaAuthzProvider</name>
1677 <description>Plug an authorization provider function into <module>mod_authz_core</module>
1679 <syntax>LuaAuthzProvider provider_name /path/to/lua/script.lua function_name</syntax>
1680 <contextlist><context>server config</context> </contextlist>
1681 <compatibility>2.4.3 and later</compatibility>
1684 <p>After a lua function has been registered as authorization provider, it can be used
1685 with the <directive module="mod_authz_core">Require</directive> directive:</p>
1687 <highlight language="config">
1688 LuaRoot /usr/local/apache2/lua
1689 LuaAuthzProvider foo authz.lua authz_check_foo
1694 <highlight language="lua">
1696 function authz_check_foo(r, who)
1697 if r.user ~= who then return apache2.AUTHZ_DENIED
1698 return apache2.AUTHZ_GRANTED
1704 </directivesynopsis>
1708 <name>LuaInputFilter</name>
1709 <description>Provide a Lua function for content input filtering</description>
1710 <syntax>LuaInputFilter filter_name /path/to/lua/script.lua function_name</syntax>
1711 <contextlist><context>server config</context> </contextlist>
1712 <compatibility>2.5.0 and later</compatibility>
1715 <p>Provides a means of adding a Lua function as an input filter.
1716 As with output filters, input filters work as coroutines,
1717 first yielding before buffers are sent, then yielding whenever
1718 a bucket needs to be passed down the chain, and finally (optionally)
1719 yielding anything that needs to be appended to the input data. The
1720 global variable <code>bucket</code> holds the buckets as they are passed
1721 onto the Lua script:
1724 <highlight language="config">
1725 LuaInputFilter myInputFilter /www/filter.lua input_filter
1726 <FilesMatch "\.lua>
1727 SetInputFilter myInputFilter
1730 <highlight language="lua">
1732 Example input filter that converts all POST data to uppercase.
1734 function input_filter(r)
1735 print("luaInputFilter called") -- debug print
1736 coroutine.yield() -- Yield and wait for buckets
1737 while bucket do -- For each bucket, do...
1738 local output = string.upper(bucket) -- Convert all POST data to uppercase
1739 coroutine.yield(output) -- Send converted data down the chain
1741 -- No more buckets available.
1742 coroutine.yield("&filterSignature=1234") -- Append signature at the end
1746 The input filter supports denying/skipping a filter if it is deemed unwanted:
1748 <highlight language="lua">
1749 function input_filter(r)
1751 return -- Simply deny filtering, passing on the original content instead
1753 coroutine.yield() -- wait for buckets
1754 ... -- insert filter stuff here
1758 See "<a href="#modifying_buckets">Modifying contents with Lua
1759 filters</a>" for more information.
1762 </directivesynopsis>
1765 <name>LuaOutputFilter</name>
1766 <description>Provide a Lua function for content output filtering</description>
1767 <syntax>LuaOutputFilter filter_name /path/to/lua/script.lua function_name</syntax>
1768 <contextlist><context>server config</context> </contextlist>
1769 <compatibility>2.5.0 and later</compatibility>
1772 <p>Provides a means of adding a Lua function as an output filter.
1773 As with input filters, output filters work as coroutines,
1774 first yielding before buffers are sent, then yielding whenever
1775 a bucket needs to be passed down the chain, and finally (optionally)
1776 yielding anything that needs to be appended to the input data. The
1777 global variable <code>bucket</code> holds the buckets as they are passed
1778 onto the Lua script:
1781 <highlight language="config">
1782 LuaOutputFilter myOutputFilter /www/filter.lua output_filter
1783 <FilesMatch "\.lua>
1784 SetOutputFilter myOutputFilter
1787 <highlight language="lua">
1789 Example output filter that escapes all HTML entities in the output
1791 function output_filter(r)
1792 coroutine.yield("(Handled by myOutputFilter)<br/>\n") -- Prepend some data to the output,
1793 -- yield and wait for buckets.
1794 while bucket do -- For each bucket, do...
1795 local output = r:escape_html(bucket) -- Escape all output
1796 coroutine.yield(output) -- Send converted data down the chain
1798 -- No more buckets available.
1802 As with the input filter, the output filter supports denying/skipping a filter
1803 if it is deemed unwanted:
1805 <highlight language="lua">
1806 function output_filter(r)
1807 if not r.content_type:match("text/html") then
1808 return -- Simply deny filtering, passing on the original content instead
1810 coroutine.yield() -- wait for buckets
1811 ... -- insert filter stuff here
1815 See "<a href="#modifying_buckets">Modifying contents with Lua filters</a>" for more
1819 </directivesynopsis>