forked from openresty/lua-nginx-module
-
Notifications
You must be signed in to change notification settings - Fork 0
/
README
5132 lines (3631 loc) · 180 KB
/
README
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Name
ngx_lua - Embed the power of Lua into Nginx
*This module is not distributed with the Nginx source.* See the
installation instructions.
Status
This module is under active development and is production ready.
Version
This document describes ngx_lua v0.5.5
(<https://github.com/chaoslawful/lua-nginx-module/tags>) released on 4
July 2012.
Synopsis
# set search paths for pure Lua external libraries (';;' is the default path):
lua_package_path '/foo/bar/?.lua;/blah/?.lua;;';
# set search paths for Lua external libraries written in C (can also use ';;'):
lua_package_cpath '/bar/baz/?.so;/blah/blah/?.so;;';
server {
location /inline_concat {
# MIME type determined by default_type:
default_type 'text/plain';
set $a "hello";
set $b "world";
# inline Lua script
set_by_lua $res "return ngx.arg[1]..ngx.arg[2]" $a $b;
echo $res;
}
location /rel_file_concat {
set $a "foo";
set $b "bar";
# script path relative to nginx prefix
# $ngx_prefix/conf/concat.lua contents:
#
# return ngx.arg[1]..ngx.arg[2]
#
set_by_lua_file $res conf/concat.lua $a $b;
echo $res;
}
location /abs_file_concat {
set $a "fee";
set $b "baz";
# absolute script path not modified
set_by_lua_file $res /usr/nginx/conf/concat.lua $a $b;
echo $res;
}
location /lua_content {
# MIME type determined by default_type:
default_type 'text/plain';
content_by_lua "ngx.say('Hello,world!')";
}
location /nginx_var {
# MIME type determined by default_type:
default_type 'text/plain';
# try access /nginx_var?a=hello,world
content_by_lua "ngx.print(ngx.var['arg_a'], '\\n')";
}
location /request_body {
# force reading request body (default off)
lua_need_request_body on;
client_max_body_size 50k;
client_body_buffer_size 50k;
content_by_lua 'ngx.print(ngx.var.request_body)';
}
# transparent non-blocking I/O in Lua via subrequests
location /lua {
# MIME type determined by default_type:
default_type 'text/plain';
content_by_lua '
local res = ngx.location.capture("/some_other_location")
if res.status == 200 then
ngx.print(res.body)
end';
}
# GET /recur?num=5
location /recur {
# MIME type determined by default_type:
default_type 'text/plain';
content_by_lua '
local num = tonumber(ngx.var.arg_num) or 0
if num > 50 then
ngx.say("num too big")
return
end
ngx.say("num is: ", num)
if num > 0 then
res = ngx.location.capture("/recur?num=" .. tostring(num - 1))
ngx.print("status=", res.status, " ")
ngx.print("body=", res.body)
else
ngx.say("end")
end
';
}
location /foo {
rewrite_by_lua '
res = ngx.location.capture("/memc",
{ args = { cmd = 'incr', key = ngx.var.uri } }
)
';
proxy_pass http://blah.blah.com;
}
location /blah {
access_by_lua '
local res = ngx.location.capture("/auth")
if res.status == ngx.HTTP_OK then
return
end
if res.status == ngx.HTTP_FORBIDDEN then
ngx.exit(res.status)
end
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
';
# proxy_pass/fastcgi_pass/postgres_pass/...
}
location /mixed {
rewrite_by_lua_file /path/to/rewrite.lua;
access_by_lua_file /path/to/access.lua;
content_by_lua_file /path/to/content.lua;
}
# use nginx var in code path
# WARN: contents in nginx var must be carefully filtered,
# otherwise there'll be great security risk!
location ~ ^/app/(.+) {
content_by_lua_file /path/to/lua/app/root/$1.lua;
}
location / {
lua_need_request_body on;
client_max_body_size 100k;
client_body_buffer_size 100k;
access_by_lua '
-- check the client IP address is in our black list
if ngx.var.remote_addr == "132.5.72.3" then
ngx.exit(ngx.HTTP_FORBIDDEN)
end
-- check if the request body contains bad words
if ngx.var.request_body and
string.match(ngx.var.request_body, "fsck")
then
return ngx.redirect("/terms_of_use.html")
end
-- tests passed
';
# proxy_pass/fastcgi_pass/etc settings
}
}
Description
This module embeds Lua, via the standard Lua interpreter or LuaJIT, into
Nginx and by leveraging Nginx's subrequests, allows the integration of
the powerful Lua threads (Lua coroutines) into the Nginx event model.
Unlike Apache's mod_lua
(<http://httpd.apache.org/docs/2.3/mod/mod_lua.html>) and Lighttpd's
mod_magnet (<http://redmine.lighttpd.net/wiki/1/Docs:ModMagnet>), Lua
code executed using this module can be *100% non-blocking* on network
traffic as long as the Nginx API for Lua provided by this module is used
to handle requests to upstream services such as mysql, postgresql,
memcached, redis, or upstream http web services. (See
ngx.location.capture, ngx.location.capture_multi, ngx.socket.tcp,
[[HttpDrizzleModule]], ngx_postgres
(<http://github.com/FRiCKLE/ngx_postgres/>), [[HttpMemcModule]],
[[HttpRedis2Module]] and [[HttpProxyModule]] modules for details).
The Lua interpreter or LuaJIT instance is shared across all the requests
in a single nginx worker process but request contexts are segregated
using lightweight Lua coroutines. Loaded Lua modules persist in the
nginx worker process level resulting in a small memory footprint even
when under heavy loads.
Directives
lua_code_cache
syntax: *lua_code_cache on | off*
default: *lua_code_cache on*
context: *main, server, location, location if*
Enables or disables the Lua code cache for set_by_lua_file,
content_by_lua_file, rewrite_by_lua_file, and access_by_lua_file, and
also force Lua module reloading on a per-request basis.
The Lua files referenced in set_by_lua_file, content_by_lua_file,
access_by_lua_file, and rewrite_by_lua_file will not be cached and the
Lua "package.loaded" table will be cleared at the entry point of every
request (such that Lua modules will not be cached either). With this in
place, developers can adopt an edit-and-refresh approach.
Please note however, that Lua code written inline within nginx.conf such
as those specified by set_by_lua, content_by_lua, access_by_lua, and
rewrite_by_lua will *always* be cached because only the Nginx config
file parser can correctly parse the "nginx.conf" file and the only ways
to to reload the config file are to send a "HUP" signal or to restart
Nginx.
The "ngx_lua" module does not currently support the "stat" mode
available with the Apache "mod_lua" module but this is planned for
implementation in the future.
Disabling the Lua code cache is strongly discouraged for production use
and should only be used during development as it has a significant
negative impact on overall performance. In addition, race conditions
when reloading Lua modules are common for concurrent requests when the
code cache is disabled.
lua_regex_cache_max_entries
syntax: *lua_regex_cache_max_entries <num>*
default: *lua_regex_cache_max_entries 1024*
context: *http*
Specifies the maximum number of entries allowed in the worker process
level compiled regex cache.
The regular expressions used in ngx.re.match, ngx.re.gmatch, ngx.re.sub,
and ngx.re.gsub will be cached within this cache if the regex option "o"
(i.e., compile-once flag) is specified.
The default number of entries allowed is 1024 and when this limit is
reached, new regular expressions will not be cached (as if the "o"
option was not specified) and there will be one, and only one, warning
in the "error.log" file:
2011/08/27 23:18:26 [warn] 31997#0: *1 lua exceeding regex cache max entries (1024), ...
Do not activate the "o" option for regular expressions (and/or "replace"
string arguments for ngx.re.sub and ngx.re.gsub) that are generated *on
the fly* and give rise to infinite variations to avoid hitting the
specified limit.
lua_package_path
syntax: *lua_package_path <lua-style-path-str>*
default: *The content of LUA_PATH environ variable or Lua's compiled-in
defaults.*
context: *main*
Sets the Lua module search path used by scripts specified by set_by_lua,
content_by_lua and others. The path string is in standard Lua path form,
and ";;" can be used to stand for the original search paths.
Since the "v0.5.0rc29" release, the special notation $prefix or
"${prefix}" can be used in the search path string to indicate the path
of the "server prefix" usually determined by the "-p PATH" command-line
option while starting the Nginx server.
lua_package_cpath
syntax: *lua_package_cpath <lua-style-cpath-str>*
default: *The content of LUA_CPATH environment variable or Lua's
compiled-in defaults.*
context: *main*
Sets the Lua C-module search path used by scripts specified by
set_by_lua, content_by_lua and others. The cpath string is in standard
Lua cpath form, and ";;" can be used to stand for the original cpath.
Since the "v0.5.0rc29" release, the special notation $prefix or
"${prefix}" can be used in the search path string to indicate the path
of the "server prefix" usually determined by the "-p PATH" command-line
option while starting the Nginx server.
init_by_lua
syntax: *init_by_lua <lua-script-str>*
context: *http*
phase: *loading-config*
Runs the Lua code specified by the argument "<lua-script-str>" on the
global Lua VM level when the Nginx master process (if any) is loading
the Nginx config file.
When Nginx receives the "HUP" signal and starts reloading the config
file, the Lua VM will also be re-created and "init_by_lua" will run
again on the new Lua VM.
Usually you can register (true) Lua global variables or pre-load Lua
modules at server start-up by means of this hook. Here is an example for
pre-loading Lua modules:
init_by_lua 'require "cjson"';
server {
location = /api {
content_by_lua '
ngx.say(cjson.encode({dog = 5, cat = 6}))
';
}
}
You can also initialize the lua_shared_dict shm storage at this phase.
Here is an example for this:
lua_shared_dict dogs 1m;
init_by_lua '
local dogs = ngx.shared.dogs;
dogs:set("Tom", 56)
';
server {
location = /api {
content_by_lua '
local dogs = ngx.shared.dogs;
ngx.say(dogs:get("Tom"))
';
}
}
But note that, the lua_shared_dict's shm storage will not be cleared
through a config reload (via the "HUP" signal, for example). So if you
do *not* want to re-initialize the shm storage in your "init_by_lua"
code in this case, then you just need to set a custom flag in the shm
storage and always check the flag in your "init_by_lua" code.
Because the Lua code in this context runs before Nginx forks its worker
processes (if any), data or code loaded here will enjoy the
Copy-on-write (COW) (<http://en.wikipedia.org/wiki/Copy-on-write>)
feature provided by many operating systems among all the worker
processes, thus saving a lot of memory.
Only a small set of the Nginx API for Lua is supported in this context:
* Logging APIs: ngx.log and print,
* Shared Dictionary API: ngx.shared.DICT.
More Nginx APIs for Lua may be supported in this context upon future
user requests.
Basically you can safely use Lua libraries that do blocking I/O in this
very context because blocking the master process during server start-up
is completely okay. Even the Nginx core does blocking I/O (at least on
resolving upstream's host names) at the configure-loading phase.
You should be very careful about potential security vulnerabilities in
your Lua code registered in this context because the Nginx master
process is often run under the "root" account.
This directive was first introduced in the "v0.5.5" release.
init_by_lua_file
syntax: *init_by_lua_file <path-to-lua-script-file>*
context: *http*
phase: *loading-config*
Equivalent to init_by_lua, except that the file specified by
"<path-to-lua-script-file>" contains the Lua code (or the Lua raw
bytecode) to be executed.
When a relative path like "foo/bar.lua" is given, they will be turned
into the absolute path relative to the "server prefix" path determined
by the "-p PATH" command-line option while starting the Nginx server.
This directive was first introduced in the "v0.5.5" release.
set_by_lua
syntax: *set_by_lua $res <lua-script-str> [$arg1 $arg2 ...]*
context: *server, server if, location, location if*
phase: *server-rewrite, rewrite*
Executes code specified in "<lua-script-str>" with optional input
arguments "$arg1 $arg2 ...", and returns string output to $res. The code
in "<lua-script-str>" can make API calls and can retrieve input
arguments from the "ngx.arg" table (index starts from 1 and increases
sequentially).
This directive is designed to execute short, fast running code blocks as
the Nginx event loop is blocked during code execution. Time consuming
code sequences should therefore be avoided.
Note that the following API functions are currently disabled within this
context:
* Output API functions (e.g., ngx.say and ngx.send_headers)
* Control API functions (e.g., ngx.exit)
* Subrequest API functions (e.g., ngx.location.capture and
ngx.location.capture_multi)
* Cosocket API functions (e.g., ngx.socket.tcp and ngx.req.socket).
In addition, note that this directive can only write out a value to a
single Nginx variable at a time. However, a workaround is possible using
the ngx.var.VARIABLE interface.
location /foo {
set $diff ''; # we have to predefine the $diff variable here
set_by_lua $sum '
local a = 32
local b = 56
ngx.var.diff = a - b; -- write to $diff directly
return a + b; -- return the $sum value normally
';
echo "sum = $sum, diff = $diff";
}
This directive can be freely mixed with all directives of the
[[HttpRewriteModule]], [[HttpSetMiscModule]], and [[HttpArrayVarModule]]
modules. All of these directives will run in the same order as they
appear in the config file.
set $foo 32;
set_by_lua $bar 'tonumber(ngx.var.foo) + 1';
set $baz "bar: $bar"; # $baz == "bar: 33"
Since the "0.5.0rc29" release, Nginx variable interpolation is disabled
in the "<lua-script-str>" argument of this directive and therefore, the
dollar sign character ("$") can be used directly.
This directive requires the ngx_devel_kit
(<https://github.com/simpl/ngx_devel_kit>) module.
set_by_lua_file
syntax: *set_by_lua_file $res <path-to-lua-script-file> [$arg1 $arg2
...]*
context: *server, server if, location, location if*
phase: *server-rewrite, rewrite*
Equivalent to set_by_lua, except that the file specified by
"<path-to-lua-script-file>" contains the Lua code to be executed.
Nginx variable interpolation is supported in the
"<path-to-lua-script-file>" argument string of this directive. But
special care must be taken for injection attacks.
When a relative path like "foo/bar.lua" is given, they will be turned
into the absolute path relative to the "server prefix" path determined
by the "-p PATH" command-line option while starting the Nginx server.
When the Lua code cache is turned on (by default), the user code is
loaded once at the first request and cached and the Nginx config must be
reloaded each time the Lua source file is modified. The Lua code cache
can be temporarily disabled during development by switching
lua_code_cache "off" in "nginx.conf" to avoid reloading Nginx.
Since the "v0.5.0rc32" release, the file specified by
"<path-to-lua-script-file>" can be a pre-compiled Lua/LuaJIT bytecode
file.
This directive requires the ngx_devel_kit
(<https://github.com/simpl/ngx_devel_kit>) module.
content_by_lua
syntax: *content_by_lua <lua-script-str>*
context: *location, location if*
phase: *content*
Acts as a "content handler" and executes Lua code string specified in
"<lua-script-str>" for every request. The Lua code may make API calls
and is executed as a new spawned coroutine in an independent global
environment (i.e. a sandbox).
Do not use this directive and other content handler directives in the
same location. For example, this directive and the proxy_pass directive
should not be used in the same location.
content_by_lua_file
syntax: *content_by_lua_file <path-to-lua-script-file>*
context: *location, location if*
phase: *content*
Equivalent to content_by_lua, except that the file specified by
"<path-to-lua-script-file>" contains the Lua code to be executed.
Nginx variables can be used in the "<path-to-lua-script-file>" string to
provide flexibility. This however carries some risks and is not
ordinarily recommended.
When a relative path like "foo/bar.lua" is given, they will be turned
into the absolute path relative to the "server prefix" path determined
by the "-p PATH" command-line option while starting the Nginx server.
When the Lua code cache is turned on (by default), the user code is
loaded once at the first request and cached and the Nginx config must be
reloaded each time the Lua source file is modified. The Lua code cache
can be temporarily disabled during development by switching
lua_code_cache "off" in "nginx.conf" to avoid reloading Nginx.
Since the "v0.5.0rc32" release, the file specified by
"<path-to-lua-script-file>" can be a pre-compiled Lua/LuaJIT bytecode
file.
rewrite_by_lua
syntax: *rewrite_by_lua <lua-script-str>*
context: *http, server, location, location if*
phase: *rewrite tail*
Acts as a rewrite phase handler and executes Lua code string specified
in "<lua-script-str>" for every request. The Lua code may make API calls
and is executed as a new spawned coroutine in an independent global
environment (i.e. a sandbox).
Note that this handler always runs *after* the standard
[[HttpRewriteModule]]. So the following will work as expected:
location /foo {
set $a 12; # create and initialize $a
set $b ""; # create and initialize $b
rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1';
echo "res = $b";
}
because "set $a 12" and "set $b """ run *before* rewrite_by_lua.
On the other hand, the following will not work as expected:
? location /foo {
? set $a 12; # create and initialize $a
? set $b ''; # create and initialize $b
? rewrite_by_lua 'ngx.var.b = tonumber(ngx.var.a) + 1';
? if ($b = '13') {
? rewrite ^ /bar redirect;
? break;
? }
?
? echo "res = $b";
? }
because "if" runs *before* rewrite_by_lua even if it is placed after
rewrite_by_lua in the config.
The right way of doing this is as follows:
location /foo {
set $a 12; # create and initialize $a
set $b ''; # create and initialize $b
rewrite_by_lua '
ngx.var.b = tonumber(ngx.var.a) + 1
if tonumber(ngx.var.b) == 13 then
return ngx.redirect("/bar");
end
';
echo "res = $b";
}
Note that the ngx_eval (<http://www.grid.net.ru/nginx/eval.en.html>)
module can be approximated by using rewrite_by_lua. For example,
location / {
eval $res {
proxy_pass http://foo.com/check-spam;
}
if ($res = 'spam') {
rewrite ^ /terms-of-use.html redirect;
}
fastcgi_pass ...;
}
can be implemented in "ngx_lua" as:
location = /check-spam {
internal;
proxy_pass http://foo.com/check-spam;
}
location / {
rewrite_by_lua '
local res = ngx.location.capture("/check-spam")
if res.body == "spam" then
ngx.redirect("/terms-of-use.html")
end
';
fastcgi_pass ...;
}
Just as any other rewrite phase handlers, rewrite_by_lua also runs in
subrequests.
Note that when calling "ngx.exit(ngx.OK)" within a rewrite_by_lua
handler, the nginx request processing control flow will still continue
to the content handler. To terminate the current request from within a
rewrite_by_lua handler, calling ngx.exit with status >= 200
("ngx.HTTP_OK") and status < 300 ("ngx.HTTP_SPECIAL_RESPONSE") for
successful quits and "ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)" (or its
friends) for failures.
If the [[HttpRewriteModule]]'s rewrite directive is used to change the
URI and initiate location re-lookups (internal redirections), then any
rewrite_by_lua or rewrite_by_lua_file code sequences within the current
location will not be executed. For example,
location /foo {
rewrite ^ /bar;
rewrite_by_lua 'ngx.exit(503)';
}
location /bar {
...
}
Here the Lua code "ngx.exit(503)" will never run. This will be the case
if "rewrite ^ /bar last" is used as this will similarly initiate an
internal redirection. If the "break" modifier is used instead, there
will be no internal redirection and the "rewrite_by_lua" code will be
executed.
The "rewrite_by_lua" code will always run at the end of the "rewrite"
request-processing phase unless rewrite_by_lua_no_postpone is turned on.
rewrite_by_lua_file
syntax: *rewrite_by_lua_file <path-to-lua-script-file>*
context: *http, server, location, location if*
phase: *rewrite tail*
Equivalent to rewrite_by_lua, except that the file specified by
"<path-to-lua-script-file>" contains the Lua code to be executed.
Nginx variables can be used in the "<path-to-lua-script-file>" string to
provide flexibility. This however carries some risks and is not
ordinarily recommended.
When a relative path like "foo/bar.lua" is given, they will be turned
into the absolute path relative to the "server prefix" path determined
by the "-p PATH" command-line option while starting the Nginx server.
When the Lua code cache is turned on (by default), the user code is
loaded once at the first request and cached and the Nginx config must be
reloaded each time the Lua source file is modified. The Lua code cache
can be temporarily disabled during development by switching
lua_code_cache "off" in "nginx.conf" to avoid reloading Nginx.
The "rewrite_by_lua_file" code will always run at the end of the
"rewrite" request-processing phase unless rewrite_by_lua_no_postpone is
turned on.
Since the "v0.5.0rc32" release, the file specified by
"<path-to-lua-script-file>" can be a pre-compiled Lua/LuaJIT bytecode
file.
access_by_lua
syntax: *access_by_lua <lua-script-str>*
context: *http, server, location, location if*
phase: *access tail*
Acts as an access phase handler and executes Lua code string specified
in "<lua-script-str>" for every request. The Lua code may make API calls
and is executed as a new spawned coroutine in an independent global
environment (i.e. a sandbox).
Note that this handler always runs *after* the standard
[[HttpAccessModule]]. So the following will work as expected:
location / {
deny 192.168.1.1;
allow 192.168.1.0/24;
allow 10.1.1.0/16;
deny all;
access_by_lua '
local res = ngx.location.capture("/mysql", { ... })
...
';
# proxy_pass/fastcgi_pass/...
}
That is, if a client IP address is in the blacklist, it will be denied
before the MySQL query for more complex authentication is executed by
access_by_lua.
Note that the ngx_auth_request
(<http://mdounin.ru/hg/ngx_http_auth_request_module/>) module can be
approximated by using access_by_lua:
location / {
auth_request /auth;
# proxy_pass/fastcgi_pass/postgres_pass/...
}
can be implemented in "ngx_lua" as:
location / {
access_by_lua '
local res = ngx.location.capture("/auth")
if res.status == ngx.HTTP_OK then
return
end
if res.status == ngx.HTTP_FORBIDDEN then
ngx.exit(res.status)
end
ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
';
# proxy_pass/fastcgi_pass/postgres_pass/...
}
As with other access phase handlers, access_by_lua will *not* run in
subrequests.
Note that when calling "ngx.exit(ngx.OK)" within a access_by_lua
handler, the nginx request processing control flow will still continue
to the content handler. To terminate the current request from within a
access_by_lua handler, calling ngx.exit with status >= 200
("ngx.HTTP_OK") and status < 300 ("ngx.HTTP_SPECIAL_RESPONSE") for
successful quits and "ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)" (or its
friends) for failures.
access_by_lua_file
syntax: *access_by_lua_file <path-to-lua-script-file>*
context: *http, server, location, location if*
phase: *access tail*
Equivalent to access_by_lua, except that the file specified by
"<path-to-lua-script-file>" contains the Lua code to be executed.
Nginx variables can be used in the "<path-to-lua-script-file>" string to
provide flexibility. This however carries some risks and is not
ordinarily recommended.
When a relative path like "foo/bar.lua" is given, they will be turned
into the absolute path relative to the "server prefix" path determined
by the "-p PATH" command-line option while starting the Nginx server.
When the Lua code cache is turned on (by default), the user code is
loaded once at the first request and cached and the Nginx config must be
reloaded each time the Lua source file is modified. The Lua code cache
can be temporarily disabled during development by switching
lua_code_cache "off" in "nginx.conf" to avoid repeatedly reloading
Nginx.
Since the "v0.5.0rc32" release, the file specified by
"<path-to-lua-script-file>" can be a pre-compiled Lua/LuaJIT bytecode
file.
header_filter_by_lua
syntax: *header_filter_by_lua <lua-script-str>*
context: *http, server, location, location if*
phase: *output-header-filter*
Uses Lua code specified in "<lua-script-str>" to define an output header
filter.
Note that the following API functions are currently disabled within this
context:
* Output API functions (e.g., ngx.say and ngx.send_headers)
* Control API functions (e.g., ngx.exit and ngx.exec)
* Subrequest API functions (e.g., ngx.location.capture and
ngx.location.capture_multi)
* Cosocket API functions (e.g., ngx.socket.tcp and ngx.req.socket).
Here is an example of overriding a response header (or adding one if
absent) in our Lua header filter:
location / {
proxy_pass http://mybackend;
header_filter_by_lua 'ngx.header.Foo = "blah"';
}
This directive was first introduced in the "v0.2.1rc20" release.
header_filter_by_lua_file
syntax: *header_filter_by_lua_file <path-to-lua-script-file>*
context: *http, server, location, location if*
phase: *output-header-filter*
Equivalent to header_filter_by_lua, except that the file specified by
"<path-to-lua-script-file>" contains the Lua code to be executed.
When a relative path like "foo/bar.lua" is given, they will be turned
into the absolute path relative to the "server prefix" path determined
by the "-p PATH" command-line option while starting the Nginx server.
Since the "v0.5.0rc32" release, the file specified by
"<path-to-lua-script-file>" can be a pre-compiled Lua/LuaJIT bytecode
file.
This directive was first introduced in the "v0.2.1rc20" release.
body_filter_by_lua
syntax: *body_filter_by_lua <lua-script-str>*
context: *http, server, location, location if*
phase: *output-body-filter*
Uses Lua code specified in "<lua-script-str>" to define an output body
filter.
The input data chunk is passed via ngx.arg[1] (as a Lua string value)
and the "eof" flag indicating the end of the response body data stream
is passed via ngx.arg[2] (as a Lua boolean value).
Behind the scene, the "eof" flag is just the "last_buf" flag of the
nginx chain link buffers. And in the context of an Nginx subrequest,
there is no "eof" flag at all, due to the underlying limitation in the
Nginx core.
The output data stream can be aborted immediately by running the
following Lua statement:
return ngx.ERROR
This will truncate the response body and usually result in incomplete
and also invalid responses.
The Lua code can pass its own modified version of the input data chunk
to the downstream Nginx output body filters by overriding ngx.arg[1]
with a Lua string or a Lua table of strings. For example, to transform
all the lowercase letters in the response body, we can just write:
location / {
proxy_pass http://mybackend;
body_filter_by_lua 'ngx.arg[1] = string.upper(ngx.arg[1])';
}
When setting "nil" or an empty Lua string value to "ngx.arg[1]", no data
chunk will be passed to the downstream Nginx output filters at all.
Likewise, new "eof" flag can also be specified by setting a boolean
value to ngx.arg[2]. For example,
location /t {
echo hello world;
echo hiya globe;
body_filter_by_lua '
local chunk = ngx.arg[1]
if string.match(chunk, "hello") then
ngx.arg[2] = true -- new eof
return
end
-- just throw away any remaining chunk data
ngx.arg[1] = nil
';
}
Then "GET /t" will just return the output
hello world
That is, when the body filter sees a chunk containing the word "hello",
then it will set the "eof" flag to true immediately, resulting in
truncated but still valid responses.
When the Lua code may change the length of the response body, then it is
required to always clear out the "Content-Length" response header (if
any) in a header filter to enforce streaming output, as in
location /foo {
# fastcgi_pass/proxy_pass/...
header_filter_by_lua 'ngx.header.content_length = nil';
body_filter_by_lua 'ngx.arg[1] = {string.len(arg[1]), "\n"}'
}
Note that the following API functions are currently disabled within this
context:
* Output API functions (e.g., ngx.say and ngx.send_headers)
* Control API functions (e.g., ngx.exit and ngx.exec)
* Subrequest API functions (e.g., ngx.location.capture and
ngx.location.capture_multi)
* Cosocket API functions (e.g., ngx.socket.tcp and ngx.req.socket).
This directive was first introduced in the "v0.5.0rc32" release.
body_filter_by_lua_file
syntax: *body_filter_by_lua_file <path-to-lua-script-file>*
context: *http, server, location, location if*
phase: *output-body-filter*
Equivalent to body_filter_by_lua, except that the file specified by
"<path-to-lua-script-file>" contains the Lua code to be executed.
When a relative path like "foo/bar.lua" is given, they will be turned
into the absolute path relative to the "server prefix" path determined
by the "-p PATH" command-line option while starting the Nginx server.
Since the "v0.5.0rc32" release, the file specified by
"<path-to-lua-script-file>" can be a pre-compiled Lua/LuaJIT bytecode
file.
This directive was first introduced in the "v0.5.0rc32" release.
log_by_lua
syntax: *log_by_lua <lua-script-str>*
context: *http, server, location, location if*
phase: *log*
Run the Lua source code inlined as the "<lua-script-str>" at the "log"
request processing phase. This does not replace the current access logs,
but runs after.
Note that the following API functions are currently disabled within this
context:
* Output API functions (e.g., ngx.say and ngx.send_headers)
* Control API functions (e.g., ngx.exit)
* Subrequest API functions (e.g., ngx.location.capture and
ngx.location.capture_multi)
* Cosocket API functions (e.g., ngx.socket.tcp and ngx.req.socket).
Here is an example of gathering average data for
$upstream_response_time:
lua_shared_dict log_dict 5M;
server {
location / {
proxy_pass http://mybackend;
log_by_lua '
local log_dict = ngx.shared.log_dict
local upstream_time = tonumber(ngx.var.upstream_response_time)
local sum = log_dict:get("upstream_time-sum") or 0
sum = sum + upstream_time
log_dict:set("upstream_time-sum", sum)
local newval, err = log_dict:incr("upstream_time-nb", 1)
if not newval and err == "not found" then
log_dict:add("upstream_time-nb", 0)
log_dict:incr("upstream_time-nb", 1)