1 <?xml version='1.0' encoding='UTF-8' ?>
2 <!DOCTYPE manualpage SYSTEM "../style/manualpage.dtd">
3 <?xml-stylesheet type="text/xsl" href="../style/manual.en.xsl"?>
5 <!-- $LastChangedRevision: 1353955 $ -->
8 Licensed to the Apache Software Foundation (ASF) under one or more
9 contributor license agreements. See the NOTICE file distributed with
10 this work for additional information regarding copyright ownership.
11 The ASF licenses this file to You under the Apache License, Version 2.0
12 (the "License"); you may not use this file except in compliance with
13 the License. You may obtain a copy of the License at
15 http://www.apache.org/licenses/LICENSE-2.0
17 Unless required by applicable law or agreed to in writing, software
18 distributed under the License is distributed on an "AS IS" BASIS,
19 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 See the License for the specific language governing permissions and
21 limitations under the License.
24 <manualpage metafile="lua.xml.meta">
25 <parentdocument href="./">Developer</parentdocument>
27 <title>Creating hooks and scripts with mod_lua</title>
30 <p>This document expands on the <module>mod_lua</module> documentation and explores
31 additional ways of using mod_lua for writing hooks and scripts.</p>
34 <seealso><a href="../mod/mod_lua.html">mod_lua</a></seealso>
35 <seealso><a href="modguide.html">Developing modules for Apache 2.4</a></seealso>
36 <seealso><a href="request.html">Request Processing in Apache 2.4</a></seealso>
37 <seealso><a href="hooks.html">Apache 2.x Hook Functions</a></seealso>
39 <section id="introduction"><title>Introduction</title>
40 <section id="what"><title>What is mod_lua</title>
42 Stuff about what <module>mod_lua</module> is goes here.
45 <section id="contents"><title>What we will be discussing in this document</title>
47 This document will discuss several cases where <module>mod_lua</module> can be used
48 to either ease up a phase of the request processing or create more transparency in
49 the logic behind a decision made in a phase.
54 <section id="prerequisites"><title>Prerequisites</title>
56 First and foremost, you are expected to have a basic knowledge of how the Lua
57 programming language works. In most cases, we will try to be as pedagogical
58 as possible and link to documents describing the functions used in the
59 examples, but there are also many cases where it is necessary to either
60 just assume that "it works" or do some digging yourself into what the hows
61 and whys of various function calls.
68 <section id="enabling"><title>Optimizing mod_lua for production servers</title>
70 <section><title>Setting a scope for Lua states</title>
72 Setting the right <directive module="mod_lua">LuaScope</directive> setting
73 for your Lua scripts can be essential to your server's
74 performance. By default, the scope is set to <code>once</code>, which means
75 that every call to a Lua script will spawn a new Lua state that handles that
76 script and is destroyed immediately after. This option keeps the memory
77 footprint of mod_lua low, but also affects the processing speed of a request.
78 If you have the memory to spare, you can set the scope to <code>thread</code>,
79 which will make mod_lua spawn a Lua state that lasts the entirity of a thread's
80 lifetime, speeding up request processing by 2-3 times. Since mod_lua will create
81 a state for each script, this may be an expensive move, memory-wise, so to
82 compromise between speed and memory usage, you can choose the <code>server</code>
83 option to create a pool of Lua states to be used. Each request for a Lua script or
84 a hook function will then acquire a state from the pool and release it back when it's
85 done using it, allowing you to still gain a significant performance increase, while
86 keeping your memory footprint low. Some examples of possible settings are:
88 <highlight language="config">
94 As a general rule of thumb: If your server has none to low usage, use <code>once</code>
95 or <code>request</code>, if your server has low to medium usage, use the <code>server</code>
96 pool, and if it has high usage, use the <code>thread</code> setting. As your server's
97 load increases, so will the number of states being actively used, and having your scope
98 set to <code>once/request/conn</code> will stop being beneficial to your memory footprint.
101 <strong>Note:</strong> The <code>min</code> and <code>max</code> settings for the
102 <code>server</code> scope denotes the minimum and maximum states to keep in a pool per
103 server <em>process</em>, so keep this below your <code>ThreadsPerChild</code> limit.
107 <section><title>Using code caching</title>
109 By default, <module>mod_lua</module> stats each Lua script to determine whether a reload
110 (and thus, a re-interpretation and re-compilation) of a script is required. This is managed
111 through the <directive module="mod_lua">LuaCodeCache</directive> directive. If you are running
112 your scripts on a production server, and you do not need to update them regularly, it may be
113 advantageous to set this directive to the <code>forever</code> value, which will cause mod_lua
114 to skip the stat process and always reuse the compiled byte-code from the first access to the
115 script, thus speeding up the processing. For Lua hooks, this can prove to increase peformance,
116 while for scripts handled by the <code>lua-script</code> handler, the increase in performance
117 may be negligible, as files httpd will stat the files regardless.
121 <section><title>Keeping the scope clean</title>
123 For maximum performance, it is generally recommended that any initialization of libraries,
124 constants and master tables be kept outside the handle's scope:
126 <highlight language="lua">
127 --[[ This is good practice ]]--
129 require "someLibrary"
130 local masterTable = {}
131 local constant = "Foo bar baz"
137 <highlight language="lua">
138 --[[ This is bad practice ]]--
142 require "someLibrary"
143 local masterTable = {}
144 local constant = "Foo bar baz"
152 <section id="basic_remap"><title>Example 1: A basic remapping module</title>
157 <highlight language="config">
158 LuaHookTranslateName /path/too/foo.lua remap
162 <!-- BEGIN EXAMPLE CODE -->
163 <highlight language="lua">
165 Simple remap example.
166 This example will rewrite /foo/test.bar to the physical file
167 /internal/test, somewhat like how mod_alias works.
171 -- Test if the URI matches our criteria
172 local barFile = r.uri:match("/foo/([a-zA-Z0-9]+%.bar)")
174 r.filename = "/internal/" .. barFile
179 <!-- END EXAMPLE CODE -->
182 <!-- BEGIN EXAMPLE CODE -->
183 <highlight language="lua">
185 Advanced remap example.
186 This example will evaluate some conditions, and based on that,
187 remap a file to one of two destinations, using a rewrite map.
193 source = [[^/photos/(.+)\.png$]],
194 destination = [[/uploads/www/$1.png]],
198 source = [[^/ext/(.*)$]],
199 destination = [[http://www.example.com/$1]],
204 function interpolateString(s,v)
205 return s:gsub("%$(%d+)", function(a) return v[tonumber(a)] end)
209 -- browse through the rewrite map
210 for key, entry in pairs(map) do
211 -- Match source regex against URI
212 local match = apache2.regex(r, entry.source, r.uri) then
213 if match and match[0] then
214 r.filename = interpolateString(entry.destination, match)
215 -- Is this a proxied remap?
217 r.handler = "proxy-server" -- tell mod_proxy to handle this
218 r.proxyreq = apache2.PROXYREQ_REVERSE -- We'll want to do a reverse proxy
219 r.filename = "proxy:" .. r.filename -- Add the proxy scheme to the destination
224 return apache2.DECLINED
227 <!-- END EXAMPLE CODE -->
237 <section id="mass_vhost"><title>Example 2: Mass virtual hosting</title>
242 <highlight language="config">
243 LuaHookTranslateName /path/too/foo.lua mass_vhost
247 <!-- BEGIN EXAMPLE CODE -->
248 <highlight language="lua">
250 Simple mass vhost script
251 This example will check a map for a virtual host and rewrite filename and
252 document root accordingly.
256 { domain = "example.com", home = "/www/example.com" },
257 { domain = "example.org", home = "/nfs/ext1/example.org" }
260 function mass_vhost(r)
261 -- Match against our hostname
262 for key, entry in pairs(vhosts) do
263 -- match against either host or *.host:
264 if apache2.strcmp_match(r.hostname, entry.domain) or
265 apache2.strcmp_match(r.hostname, "*." .. entry.domain) then
266 -- If it matches, rewrite filename and set document root
267 local filename = r.filename:sub(r.document_root:len()+1)
268 r.filename = entry.home .. filename
269 apahce2.set_document_root(entry.home)
273 return apache2.DECLINED
276 <!-- END EXAMPLE CODE -->
279 <!-- BEGIN EXAMPLE CODE -->
280 <highlight language="lua">
282 Advanced mass virtual hosting
283 This example will query a database for vhost entries and save them for
284 60 seconds before checking for updates. For best performance, such scripts
285 should generally be run with LuaScope set to 'thread' or 'server'
288 local cached_vhosts = {}
291 -- Function for querying the database for saved vhost entries
292 function query_vhosts(host)
293 if not cached_vhosts[host] or (cached_vhosts[host] and cached_vhosts[host].updated < os.time() - timeout) then
294 local db = apache2.dbopen(r,"mod_dbd")
295 local _host = db:escape(_host)
296 local res, err = db:query( ("SELECT `destination` FROM `vhosts` WHERE `hostname` = '%s' LIMIT 1"):format(_host) )
297 if res and #res == 1 then
298 cached_vhosts[host] = { updated = os.time(), destination = res[1][1] }
300 cached_vhosts[host] = nil
304 if cached_vhosts[host] then
305 return cached_vhosts[host].destination
311 function mass_vhost(r)
312 -- Check whether the hostname is in our database
313 local destination = query_vhosts(r.hostname)
315 -- If found, rewrite and change document root
316 local filename = r.filename:sub(r.document_root:len()+1)
317 r.filename = destination .. filename
318 apahce2.set_document_root(destination)
321 return apache2.DECLINED
324 <!-- END EXAMPLE CODE -->
334 <section id="basic_auth"><title>Example 3: A basic authorization hook</title>
336 <highlight language="config">
337 LuaHookAuthChecker /path/too/foo.lua check_auth
340 <!-- BEGIN EXAMPLE CODE -->
341 <highlight language="lua">
343 A simple authentication hook that checks a table containing usernames and
344 passwords of two accounts.
347 bob = 'somePassword',
351 -- Function for parsing the Authorization header into a username and a password
352 function parse_auth(str)
353 local user,pass = nil, nil
354 if str and str:len() > 0 then
355 str = apache2.base64_decode(auth):sub(7));
356 user, pass = auth:match("([^:]+)%:([^:]+)")
361 -- The authentication hook
362 function check_auth(r)
363 local user, pass = parse_auth(r.headers_in['Authorization'])
364 local authenticated = false
365 if user and pass then
366 if accounts[user] and accounts[user] == pass then
371 r.headers_out["WWW-Authenticate"] = 'Basic realm="Super secret zone"'
372 if not authenticated then
379 <!-- END EXAMPLE CODE -->
382 <!-- BEGIN EXAMPLE CODE -->
383 <highlight language="lua">
385 An advanced authentication checker with a database backend,
386 caching account entries for 1 minute
389 local timeout = 60 -- Set account info to be refreshed every minute
392 -- Function for parsing the Authorization header into a username and a password
393 function parse_auth(str)
394 local user,pass = nil, nil
395 if str and str:len() > 0 then
396 str = apache2.base64_decode(auth):sub(7));
397 user, pass = auth:match("([^:]+)%:([^:]+)")
402 -- Function for querying the database for the account's password (stored as a salted SHA-1 hash)
403 function fetch_password(user)
404 if not accounts[user] or (accounts[user] and accounts[user].updated < os.time() - timeout) then
405 local db = apache2.dbopen(r, "mod_dbd")
406 local usr = db:escape(user)
407 local res, err = db:query( ("SELECT `password` FROM `accounts` WHERE `user` = '%s' LIMIT 1"):format(usr) )
408 if res and #res == 1 then
409 accounts[user] = { updated = os.time(), password = res[1][1] }
415 if accounts[user] then
416 return accounts[user].password
422 -- The authentication hook
423 function check_auth(r)
424 local user, pass = parse_auth(r.headers_in['Authorization'])
425 local authenticated = false
426 if user and pass then
427 pass = apache2.sha1("addSomeSalt" .. pass)
428 local stored_pass = fetch_password(user)
429 if stored_pass and pass == stored_pass then
434 r.headers_out["WWW-Authenticate"] = 'Basic realm="Super secret zone"'
435 if not authenticated then
442 <!-- END EXAMPLE CODE -->
447 <section id="authz"><title>Example 4: Authorization using LuaAuthzProvider</title>
449 <highlight language="config">
450 LuaAuthzProvider rights /path/to/lua/script.lua rights_handler
451 <Directory /www/private>
452 Require rights member
454 <Directory /www/admin>
459 <highlight language="lua">
461 This script has two user groups; members and admins, and whichever
462 is refered to by the "Require rights" directive is checked to see
463 if the authenticated user belongs to this group.
466 local members = { "rbowen", "humbedooh", "igalic", "covener" }
467 local admins = { "humbedooh" }
469 function rights_handler(r, what)
470 if r.user == nil then
471 return apache2.AUTHZ_AUTHZ_DENIED_NO_USER
473 if what == "member" then
474 for k, v in pairs(members) do
476 return apache2.AUTHZ_GRANTED
479 elseif what == "admin" then
480 for k, v in pairs(admins) do
482 return apache2.AUTHZ_GRANTED
486 return apache2.AUTHZ_DENIED
491 <section id="map_handler"><title>Example 5: Overlays using LuaMapHandler</title>
493 <highlight language="config">
494 LuaMapHandler ^/portal/([a-z]+)/ /path/to/lua/script.lua handle_$1
498 <section id="mod_status_lua"><title>Example 6: Basic Lua scripts</title>
507 <section id="String_manipulation">
508 <title>HTTPd bindings: String manipulation</title>
510 <a href="#apache2.base64_encode">apache2.base64_encode</a>
512 <a href="#apache2.base64_decode">apache2.base64_decode</a>
514 <a href="#apache2.escape">apache2.escape</a>
516 <a href="#apache2.unescape">apache2.unescape</a>
518 <a href="#apache2.escapehtml">apache2.escapehtml</a>
520 <a href="#apache2.md5">apache2.md5</a>
522 <a href="#apache2.sha1">apache2.sha1</a>
524 <a href="#apache2.os_escape_path">apache2.os_escape_path</a>
526 <a href="#apache2.escape_logitem">apache2.escape_logitem</a>
529 <section id="apache2.base64_decode">
530 <title>apache2.base64_decode(
531 request_rec<em> r</em>, string<em> string</em>
535 Decodes a base64-encoded string
547 <td>The mod_lua request handle</td>
551 <td>The string to decode</td>
555 <em>Return value(s):</em>
557 The base64-decoded string.
562 <highlight language="lua">
563 local str = "This is a test"
564 local encoded = apache2.base64_encode(str)
565 local decoded = apache2.base64_decode(encoded)
569 <section id="apache2.base64_encode">
570 <title>apache2.base64_encode(
571 request_rec<em> r</em>, string<em> string</em>
575 Encodes a string using the base64 encoding scheme.
587 <td>The mod_lua request handle</td>
591 <td>The string to encode</td>
597 <highlight language="lua">
598 local str = "This is a test"
599 local encoded = apache2.base64_encode(str)
600 local decoded = apache2.base64_decode(encoded)
604 <section id="apache2.escape">
605 <title>apache2.escape(
606 request_rec<em> r</em>, string<em> string</em>
622 <td>The mod_lua request handle</td>
626 <td>The string to escape</td>
630 <em>Return value(s):</em>
632 The URL-escaped string.
637 <highlight language="lua">
638 local str = "This is a test"
639 local escaped = apache2.escape(str)
640 print(escaped) -- prints "This+is+a+test"
644 <section id="apache2.escape_logitem">
645 <title>apache2.escape_logitem(
646 request_rec<em> r</em>, string<em> path</em>
650 Escape a string for logging
662 <td>The mod_lua request handle</td>
666 <td>The string to escape</td>
670 <em>Return value(s):</em>
676 <section id="apache2.escapehtml">
677 <title>apache2.escapehtml(
678 request_rec<em> r</em>, string<em> html</em>, boolean<em> toasc</em>
682 Escapes HTML entities.
694 <td>The mod_lua request handle</td>
698 <td>The HTML code to escape</td>
702 <td>Whether to escape all non-ASCI characters as &#nnn;</td>
706 <em>Return value(s):</em>
708 The escaped HTML code.
713 <highlight language="lua">
714 local html = "<b>Testing!</b>"
715 local escaped = apache2.escapehtml(html)
716 r:puts(escaped) -- prints "&lt;b&gt;Testing!&lt;/b&gt;"
720 <section id="apache2.md5">
722 request_rec<em> r</em>, string<em> string</em>
726 Computes an MD5 digest sum based on a string (binary safe)
738 <td>The mod_lua request handle</td>
742 <td>The (binary) string to digest</td>
746 <em>Return value(s):</em>
748 The MD5 digest sum of the data provided
753 <highlight language="lua">
754 local text = "The quick brown fox jumps over the lazy dog"
755 local md5 = apache2.md51(text)
756 r:puts(md5) -- prints out "9e107d9d372bb6826bd81d3542a419d6"
760 <section id="apache2.os_escape_path">
761 <title>apache2.os_escape_path(
762 request_rec<em> r</em>, string<em> path</em>, boolean<em> partial</em>
766 convert an OS path to a URL in an OS dependant way.
778 <td>The mod_lua request handle</td>
782 <td>The path to convert</td>
786 <td>partial if set, assume that the path will be appended to something with a '/' in it (and thus does not prefix "./")</td>
790 <em>Return value(s):</em>
797 <highlight language="lua">
798 local path = ap_os_escape_path("C:/foo/bar.txt")
802 <section id="apache2.sha1">
804 request_rec<em> r</em>, string<em> string</em>
808 Computes an SHA-1 digest sum based on a string (binary safe)
820 <td>The mod_lua request handle</td>
824 <td>The (binary) string to digest</td>
828 <em>Return value(s):</em>
830 The SHA-1 digest sum of the data provided
835 <highlight language="lua">
836 local text = "The quick brown fox jumps over the lazy dog"
837 local sha1 = apache2.sha1(text)
838 r:puts(sha1) -- prints out "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"
842 <section id="apache2.unescape">
843 <title>apache2.unescape(
844 request_rec<em> r</em>, string<em> string</em>
848 unescapes an URL-escaped string
860 <td>The mod_lua request handle</td>
864 <td>The string to unescape</td>
868 <em>Return value(s):</em>
870 The URL-unescaped string
875 <highlight language="lua">
876 local str = "This+is+a+test"
877 local unescaped = apache2.unescape(str)
878 print(unescaped) -- prints "This is a test"
884 <section id="Request_handling">
885 <title>HTTPd bindings: Request handling</title>
887 <a href="#apache2.requestbody">apache2.requestbody</a>
889 <a href="#apache2.add_input_filter">apache2.add_input_filter</a>
891 <a href="#apache2.get_basic_auth_pw">apache2.get_basic_auth_pw</a>
893 <a href="#apache2.set_document_root">apache2.set_document_root</a>
895 <a href="#apache2.set_context_prefix">apache2.set_context_prefix</a>
897 <a href="#apache2.get_server_name_for_url">apache2.get_server_name_for_url</a>
899 <a href="#apache2.set_keepalive">apache2.set_keepalive</a>
901 <a href="#apache2.make_etag">apache2.make_etag</a>
903 <a href="#apache2.send_interim_response">apache2.send_interim_response</a>
906 <section id="apache2.add_input_filter">
907 <title>apache2.add_input_filter(
908 request_rec<em> r</em>, string<em> filter</em>
912 Adds an input filter to the request
924 <td>The mod_lua request handle</td>
928 <td>The name of the filter handler to add</td>
934 <highlight language="lua">
935 apache2.add_input_filter(r, "SPAM_FILTER") -- Check input for spam..?
939 <section id="apache2.get_basic_auth_pw">
940 <title>apache2.get_basic_auth_pw(
941 request_rec<em> r</em>
945 Returns the password from a basic authorization request or nil if none was supplied
957 <td>The mod_lua request handle</td>
961 <em>Return value(s):</em>
963 The password from a basic authorization request or nil if none was supplied
967 <section id="apache2.get_server_name_for_url">
968 <title>apache2.get_server_name_for_url(
969 request_rec<em> r</em>
973 Get the current server name from the request for the purposes of using in a URL.
974 If the server name is an IPv6 literal address, it will be returned in URL format (e.g., "[fe80::1]").
986 <td>The mod_lua request handle</td>
991 <section id="apache2.make_etag">
992 <title>apache2.make_etag(
993 request_rec<em> r</em>, boolean<em> force_weak</em>
997 Constructs an entity tag from the resource information. If it's a real file, build in some of the file characteristics.
1005 <th>Description</th>
1009 <td>The mod_lua request handle</td>
1013 <td>force_weak Force the entity tag to be weak - it could be modified again in as short an interval.</td>
1017 <em>Return value(s):</em>
1023 <section id="apache2.requestbody">
1024 <title>apache2.requestbody(
1025 request_rec<em> r</em>, number<em> size</em>, string<em> filename</em>
1029 Reads the request body. If a filename is specified, the request body will be written to that file and the number of bytes written returned, otherwise, the full request body will be returned as a string.
1037 <th>Description</th>
1041 <td>The mod_lua request handle</td>
1045 <td>The maximum size allowed, or 0/nil for unlimited size</td>
1049 <td>The file to save the output to, or nil to return it as a string</td>
1053 <em>Return value(s):</em>
1055 The number of bytes written if a filename was specified, otherwise it returns the entire request body as a string.
1060 <highlight language="lua">
1061 if tonumber(r.headers_in['Content-Length'] or 0) < 10000 then
1062 local smallfile = apache2.requestbody(r, 10000) -- fetch a small file into memory
1063 r:puts("I saved the uploaded file in memory")
1065 local read = apache2.requestbody(r, 0, "/path/to/tmp")
1066 r:puts("I saved the uploaded file in a temp directory. Total bytes written was: ", read)
1071 <section id="apache2.send_interim_response">
1072 <title>apache2.send_interim_response(
1073 request_rec<em> r</em>, boolean<em> send_headers</em>
1077 Sends an interim (HTTP 1xx) response immediately.
1085 <th>Description</th>
1089 <td>The mod_lua request handle</td>
1092 <td>send_headers</td>
1093 <td>send_headers Whether to send&clear headers in r->headers_out</td>
1099 <highlight language="lua">
1100 apache2.send_interim_response(r, false)
1104 <section id="apache2.set_context_prefix">
1105 <title>apache2.set_context_prefix(
1106 request_rec<em> r</em>, string<em> prefix</em>, string<em> document</em>
1110 Set context_prefix and context_document_root for a request.
1118 <th>Description</th>
1122 <td>The mod_lua request handle</td>
1126 <td>The URI prefix, without trailing slash</td>
1130 <td>The corresponding directory on disk, without trailing slash</td>
1135 <section id="apache2.set_document_root">
1136 <title>apache2.set_document_root(
1137 request_rec<em> r</em>, string<em> root</em>
1141 Sets the document root of the request.
1149 <th>Description</th>
1153 <td>The mod_lua request handle</td>
1163 <highlight language="lua">
1164 -- Suppose our real document root is /var/bar, then...
1165 if r.hostname == "www.foo.com" then
1166 apache2.set_document_root(r, "/www/foo") -- change document root on the fly
1171 <section id="apache2.set_keepalive">
1172 <title>apache2.set_keepalive(
1173 request_rec<em> r</em>
1177 Sets the keepalive status for this request
1185 <th>Description</th>
1189 <td>The mod_lua request handle</td>
1193 <em>Return value(s):</em>
1195 True if keepalive can be set, false otherwise
1201 <section id="Parser_functions">
1202 <title>HTTPd bindings: Parser functions</title>
1204 <a href="#apache2.expr">apache2.expr</a>
1206 <a href="#apache2.regex">apache2.regex</a>
1208 <a href="#apache2.strcmp_match">apache2.strcmp_match</a>
1211 <section id="apache2.expr">
1212 <title>apache2.expr(
1213 request_rec<em> r</em>, string<em> expression</em>
1217 Evaluates an ap_expr (think <If ...>) expression and returns true if the expression is true, false otherwise. A second value containing an error string is returned if the expression is invalid.
1225 <th>Description</th>
1229 <td>The mod_lua request handle</td>
1237 <em>Return value(s):</em>
1239 True if the expression evaluates as true, false if the expression doesn't evaluate as true or if an error occurred. If an error occurred during parsing, a second value will be returned, containng the error string.
1244 <highlight language="lua">
1245 if apache2.expr("%{REQUEST_URI} =~ /force-gzip") then
1246 r:addoutputfilter("DEFLATE")
1251 <section id="apache2.regex">
1252 <title>apache2.regex(
1253 request_rec<em> r</em>, string<em> expression</em>, string<em> source</em>
1257 Evaluates a regular expression and, if it matches the source string, captures the variables and returns the matches as a table. On error, it returns nil.
1265 <th>Description</th>
1269 <td>The mod_lua request handle</td>
1273 <td>expression to match for</td>
1277 <td>the source string to capture from</td>
1281 <em>Return value(s):</em>
1283 True if the expression evaluates as true, false if the expression doesn't evaluate as true or if an error occurred. If an error occurred during parsing, a second value will be returned, containng the error string.
1288 <highlight language="lua">
1289 local matches = apache2.regex(r, [[(\S+) kitty]], "Hello kitty")
1290 if matches and matches[1] then
1291 r:puts("You said ", matches[1], " to kitty")
1296 <section id="apache2.strcmp_match">
1297 <title>apache2.strcmp_match(
1298 string<em> str</em>, string<em> expexted</em>, boolean<em> ignoreCase</em>
1302 Determines if a string matches a pattern containing the wildcards '?' or '*'
1310 <th>Description</th>
1314 <td>The string to check</td>
1318 <td>The pattern to match against</td>
1322 <td>Whether to ignore case when matching</td>
1326 <em>Return value(s):</em>
1328 True if the two strings match, false otherwise.
1333 <highlight language="lua">
1334 if apache2.strcmp_match("foo.bar", "foo.*") then
1335 r:puts("It matches!")
1342 <section id="Server_settings">
1343 <title>HTTPd bindings: Server settings</title>
1345 <a href="#apache2.add_version_component">apache2.add_version_component</a>
1347 <a href="#apache2.mpm_query">apache2.mpm_query</a>
1349 <a href="#apache2.terminate">apache2.terminate</a>
1351 <a href="#apache2.scoreboard_process">apache2.scoreboard_process</a>
1353 <a href="#apache2.scoreboard_worker">apache2.scoreboard_worker</a>
1355 <a href="#apache2.module_info">apache2.module_info</a>
1357 <a href="#apache2.loaded_modules">apache2.loaded_modules</a>
1359 <a href="#apache2.runtime_dir_relative">apache2.runtime_dir_relative</a>
1361 <a href="#apache2.server_info">apache2.server_info</a>
1363 <a href="#apache2.state_query">apache2.state_query</a>
1365 <a href="#apache2.custom_response">apache2.custom_response</a>
1367 <a href="#apache2.exists_config_define">apache2.exists_config_define</a>
1370 <section id="apache2.add_version_component">
1371 <title>apache2.add_version_component(
1372 request_rec<em> r</em>, string<em> component</em>
1376 Adds a component to the server description and banner strings
1384 <th>Description</th>
1388 <td>The mod_lua request handle</td>
1392 <td>The component to add</td>
1398 <highlight language="lua">
1399 if not apache2.banner():match("FooModule") then -- Make sure we haven't added it already
1400 apache2.add_version_component(r, "FooModule/1.0")
1405 <section id="apache2.custom_response">
1406 <title>apache2.custom_response(
1407 request_rec<em> r</em>, number<em> status</em>, string<em> string</em>
1411 Install a custom response handler for a given status
1419 <th>Description</th>
1423 <td>The mod_lua request handle</td>
1427 <td>The status for which the custom response should be used</td>
1431 <td>The custom response. This can be a static string, a file or a URL</td>
1437 <highlight language="lua">
1438 apache2.custom_response(r, 404, "Not found!!")
1442 <section id="apache2.exists_config_define">
1443 <title>apache2.exists_config_define(
1444 string<em> name</em>
1448 Checks for a definition from the server command line
1456 <th>Description</th>
1460 <td>The define to check for</td>
1466 <highlight language="lua">
1467 if apache2.exists_config_define("FOO") then
1468 r:puts("This server was started with -DFOO")
1473 <section id="apache2.loaded_modules">
1474 <title>apache2.loaded_modules(
1479 Returns a table containing the name (c filename) of all loaded modules
1486 <em>Return value(s):</em>
1488 A table containing the name (c filename) of all loaded modules
1492 <section id="apache2.module_info">
1493 <title>apache2.module_info(
1494 string<em> c</em>, string<em> file</em>
1498 Returns information about a specific module (if loaded)
1506 <th>Description</th>
1518 <em>Return value(s):</em>
1520 The various commands available to this module as a table, or nil if the module wasn't found.
1524 <section id="apache2.mpm_query">
1525 <title>apache2.mpm_query(
1530 Queries the MPM for a specific value
1538 <th>Description</th>
1546 <em>Return value(s):</em>
1552 <section id="apache2.runtime_dir_relative">
1553 <title>apache2.runtime_dir_relative(
1554 request_rec<em> r</em>, string<em> file</em>
1558 Returns the path of a file relative to the default runtime directory
1566 <th>Description</th>
1570 <td>The mod_lua request handle</td>
1578 <em>Return value(s):</em>
1580 The path of a file relative to the default runtime directory
1584 <section id="apache2.scoreboard_process">
1585 <title>apache2.scoreboard_process(
1586 request_rec<em> r</em>, number<em> child</em>
1590 Returns the scoreboard for a server daemon as a table
1598 <th>Description</th>
1602 <td>The mod_lua request handle</td>
1606 <td>The server child to query</td>
1610 <em>Return value(s):</em>
1612 The scoreboard for a server daemon as a table
1616 <section id="apache2.scoreboard_worker">
1617 <title>apache2.scoreboard_worker(
1618 request_rec<em> r</em>, number<em> child</em>, number<em> thread</em>
1622 Returns the scoreboard for a single thread as a table
1630 <th>Description</th>
1634 <td>The mod_lua request handle</td>
1638 <td>The server child to query</td>
1642 <td>The thread to query</td>
1646 <em>Return value(s):</em>
1648 The scoreboard for a single thread as a table
1652 <section id="apache2.server_info">
1653 <title>apache2.server_info(
1658 Returns a table with information about the server program
1665 <em>Return value(s):</em>
1667 A table with information about the server program
1671 <section id="apache2.state_query">
1672 <title>apache2.state_query(
1673 number<em> field</em>
1677 Query the server for some state information
1685 <th>Description</th>
1689 <td>Which information is requested</td>
1695 <highlight language="lua">
1696 local gen = apache2.state_query(2)
1697 r:puts("This is generation no. " .. gen .. " of the top-level parent")
1701 <section id="apache2.terminate">
1702 <title>apache2.terminate(
1707 Kills off a server process. This has no other use than to show how dangerous mod_lua can be ;)
1716 <section id="Database_connectivity">
1717 <title>HTTPd bindings: Database connectivity</title>
1719 <a href="#apache2.dbopen">apache2.dbopen</a>
1721 <a href="#db:query">db:query</a>
1723 <a href="#db:do">db:do</a>
1725 <a href="#db:close">db:close</a>
1728 <section id="apache2.dbopen">
1729 <title>apache2.dbopen(
1730 request_rec<em> r</em>, string<em> dbtype</em>, string<em> conn_string</em>
1734 Opens up a new database connection. See the DB functions for mod_pLua for more info on this.
1742 <th>Description</th>
1746 <td>The mod_lua request handle</td>
1753 <td>conn_string</td>
1754 <td>connection string</td>
1758 <em>Return value(s):</em>
1760 The database connection as a table with functions, or nil if the connection failed. If a connection failed, a second argument (string) with the error code is returned.
1765 <highlight language="lua">
1766 local db, error = apache2.dbopen(r, "mod_dbd")
1768 r:puts("DB error: ", error)
1775 <section id="db:close">
1777 request_rec<em> r</em>
1781 Closes a database connection
1789 <th>Description</th>
1793 <td>The mod_lua request handle</td>
1799 <highlight language="lua">
1800 local db = apache2.dbopen(r, "mod_dbd") -- open a db connection
1801 db:close() -- close it down
1805 <section id="db:do">
1807 request_rec<em> r</em>, string<em> query</em>
1811 Executes a statement that doesn't return a result set
1819 <th>Description</th>
1823 <td>The mod_lua request handle</td>
1827 <td>The SQL statement to execute</td>
1831 <em>Return value(s):</em>
1833 If the statement is valid, a table of results are returned. If an error occurred, the first return value is false and the second return value is a string containing an error message.
1838 <highlight language="lua">
1839 local db = apache2.dbopen(r, "mod_dbd")
1840 local affected = db:do("DELETE FROM `table` WHERE 1")
1842 r:puts("Affected ", affected, " rows")
1847 <section id="db:query">
1849 request_rec<em> r</em>, string<em> query</em>
1853 Queries the database for information using the specified statement.
1861 <th>Description</th>
1865 <td>The mod_lua request handle</td>
1869 <td>The SQL statement to execute</td>
1873 <em>Return value(s):</em>
1875 If the statement is valid, a table of results are returned. If an error occurred, the first return value is false and the second return value is a string containing an error message.
1880 <highlight language="lua">
1881 local db = apache2.dbopen(r, "mod_dbd")
1882 local result, error = db:query("SELECT * FROM `table` WHERE 1")
1884 for key, value in pairs(result)
1885 r:puts( ("row %s: %s\n"):format(key, table.concat(value, ", ")) )
1892 <section id="Miscellaneous">
1893 <title>HTTPd bindings: Miscellaneous</title>
1895 <a href="#apache2.clock">apache2.clock</a>
1897 <a href="#apache2.sleep">apache2.sleep</a>
1900 <section id="apache2.clock">
1901 <title>apache2.clock(
1906 Returns the current time in microseconds.
1913 <em>Return value(s):</em>
1915 The current time in microseconds.
1919 <section id="apache2.sleep">
1920 <title>apache2.sleep(
1921 number<em> seconds</em>
1925 Sleeps for a while. Floating point values can be used to sleep for less than a second.
1933 <th>Description</th>
1937 <td>The number of seconds to sleep.</td>
1943 <highlight language="lua">
1946 apache2.sleep(0.25) -- sleep for a quarter second.