yannstatic/static/2019/12/25/ngx_lua.html

8438 lines
700 KiB
HTML
Raw Normal View History

2024-10-31 20:18:37 +01:00
<!DOCTYPE html><html lang="fr">
<head><meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"><title>ngx_lua - YannStatic</title>
<meta name="description" content="Name">
<link rel="canonical" href="https://static.rnmkcy.eu/2019/12/25/ngx_lua.html"><link rel="alternate" type="application/rss+xml" title="YannStatic" href="/feed.xml">
<!-- - include head/favicon.html - -->
<link rel="shortcut icon" type="image/png" href="/assets/favicon/favicon.png"><link rel="stylesheet" href="/assets/css/main.css"><link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" ><!-- start custom head snippets --><link rel="stylesheet" href="/assets/css/expand.css">
<!-- end custom head snippets --><script>(function() {
window.isArray = function(val) {
return Object.prototype.toString.call(val) === '[object Array]';
};
window.isString = function(val) {
return typeof val === 'string';
};
window.hasEvent = function(event) {
return 'on'.concat(event) in window.document;
};
window.isOverallScroller = function(node) {
return node === document.documentElement || node === document.body || node === window;
};
window.isFormElement = function(node) {
var tagName = node.tagName;
return tagName === 'INPUT' || tagName === 'SELECT' || tagName === 'TEXTAREA';
};
window.pageLoad = (function () {
var loaded = false, cbs = [];
window.addEventListener('load', function () {
var i;
loaded = true;
if (cbs.length > 0) {
for (i = 0; i < cbs.length; i++) {
cbs[i]();
}
}
});
return {
then: function(cb) {
cb && (loaded ? cb() : (cbs.push(cb)));
}
};
})();
})();
(function() {
window.throttle = function(func, wait) {
var args, result, thisArg, timeoutId, lastCalled = 0;
function trailingCall() {
lastCalled = new Date;
timeoutId = null;
result = func.apply(thisArg, args);
}
return function() {
var now = new Date,
remaining = wait - (now - lastCalled);
args = arguments;
thisArg = this;
if (remaining <= 0) {
clearTimeout(timeoutId);
timeoutId = null;
lastCalled = now;
result = func.apply(thisArg, args);
} else if (!timeoutId) {
timeoutId = setTimeout(trailingCall, remaining);
}
return result;
};
};
})();
(function() {
var Set = (function() {
var add = function(item) {
var i, data = this._data;
for (i = 0; i < data.length; i++) {
if (data[i] === item) {
return;
}
}
this.size ++;
data.push(item);
return data;
};
var Set = function(data) {
this.size = 0;
this._data = [];
var i;
if (data.length > 0) {
for (i = 0; i < data.length; i++) {
add.call(this, data[i]);
}
}
};
Set.prototype.add = add;
Set.prototype.get = function(index) { return this._data[index]; };
Set.prototype.has = function(item) {
var i, data = this._data;
for (i = 0; i < data.length; i++) {
if (this.get(i) === item) {
return true;
}
}
return false;
};
Set.prototype.is = function(map) {
if (map._data.length !== this._data.length) { return false; }
var i, j, flag, tData = this._data, mData = map._data;
for (i = 0; i < tData.length; i++) {
for (flag = false, j = 0; j < mData.length; j++) {
if (tData[i] === mData[j]) {
flag = true;
break;
}
}
if (!flag) { return false; }
}
return true;
};
Set.prototype.values = function() {
return this._data;
};
return Set;
})();
window.Lazyload = (function(doc) {
var queue = {js: [], css: []}, sources = {js: {}, css: {}}, context = this;
var createNode = function(name, attrs) {
var node = doc.createElement(name), attr;
for (attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
node.setAttribute(attr, attrs[attr]);
}
}
return node;
};
var end = function(type, url) {
var s, q, qi, cbs, i, j, cur, val, flag;
if (type === 'js' || type ==='css') {
s = sources[type], q = queue[type];
s[url] = true;
for (i = 0; i < q.length; i++) {
cur = q[i];
if (cur.urls.has(url)) {
qi = cur, val = qi.urls.values();
qi && (cbs = qi.callbacks);
for (flag = true, j = 0; j < val.length; j++) {
cur = val[j];
if (!s[cur]) {
flag = false;
}
}
if (flag && cbs && cbs.length > 0) {
for (j = 0; j < cbs.length; j++) {
cbs[j].call(context);
}
qi.load = true;
}
}
}
}
};
var load = function(type, urls, callback) {
var s, q, qi, node, i, cur,
_urls = typeof urls === 'string' ? new Set([urls]) : new Set(urls), val, url;
if (type === 'js' || type ==='css') {
s = sources[type], q = queue[type];
for (i = 0; i < q.length; i++) {
cur = q[i];
if (_urls.is(cur.urls)) {
qi = cur;
break;
}
}
val = _urls.values();
if (qi) {
callback && (qi.load || qi.callbacks.push(callback));
callback && (qi.load && callback());
} else {
q.push({
urls: _urls,
callbacks: callback ? [callback] : [],
load: false
});
for (i = 0; i < val.length; i++) {
node = null, url = val[i];
if (s[url] === undefined) {
(type === 'js' ) && (node = createNode('script', { src: url }));
(type === 'css') && (node = createNode('link', { rel: 'stylesheet', href: url }));
if (node) {
node.onload = (function(type, url) {
return function() {
end(type, url);
};
})(type, url);
(doc.head || doc.body).appendChild(node);
s[url] = false;
}
}
}
}
}
};
return {
js: function(url, callback) {
load('js', url, callback);
},
css: function(url, callback) {
load('css', url, callback);
}
};
})(this.document);
})();
</script><script>
(function() {
var TEXT_VARIABLES = {
version: '2.2.6',
sources: {
font_awesome: 'https://use.fontawesome.com/releases/v5.0.13/css/all.css',
jquery: '/assets/js/jquery.min.js',
leancloud_js_sdk: '//cdn.jsdelivr.net/npm/leancloud-storage@3.13.2/dist/av-min.js',
chart: 'https://cdn.bootcss.com/Chart.js/2.7.2/Chart.bundle.min.js',
gitalk: {
js: 'https://cdn.bootcss.com/gitalk/1.2.2/gitalk.min.js',
css: 'https://cdn.bootcss.com/gitalk/1.2.2/gitalk.min.css'
},
valine: 'https://unpkg.com/valine/dist/Valine.min.js'
},
site: {
toc: {
selectors: 'h1,h2,h3'
}
},
paths: {
search_js: '/assets/search.js'
}
};
window.TEXT_VARIABLES = TEXT_VARIABLES;
})();
</script>
</head>
<body>
<div class="root" data-is-touch="false">
<div class="layout--page js-page-root"><!----><div class="page__main js-page-main page__viewport hide-footer has-aside has-aside cell cell--auto">
<div class="page__main-inner"><div class="page__header d-print-none"><header class="header"><div class="main">
<div class="header__title">
<div class="header__brand"><svg id="svg" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="400" height="478.9473684210526" viewBox="0, 0, 400,478.9473684210526"><g id="svgg"><path id="path0" d="M308.400 56.805 C 306.970 56.966,303.280 57.385,300.200 57.738 C 290.906 58.803,278.299 59.676,269.200 59.887 L 260.600 60.085 259.400 61.171 C 258.010 62.428,256.198 63.600,255.645 63.600 C 255.070 63.600,252.887 65.897,252.598 66.806 C 252.460 67.243,252.206 67.600,252.034 67.600 C 251.397 67.600,247.206 71.509,247.202 72.107 C 247.201 72.275,246.390 73.190,245.400 74.138 C 243.961 75.517,243.598 76.137,243.592 77.231 C 243.579 79.293,241.785 83.966,240.470 85.364 C 239.176 86.740,238.522 88.365,237.991 91.521 C 237.631 93.665,236.114 97.200,235.554 97.200 C 234.938 97.200,232.737 102.354,232.450 104.472 C 232.158 106.625,230.879 109.226,229.535 110.400 C 228.933 110.926,228.171 113.162,226.434 119.500 C 226.178 120.435,225.795 121.200,225.584 121.200 C 225.373 121.200,225.200 121.476,225.200 121.813 C 225.200 122.149,224.885 122.541,224.500 122.683 C 223.606 123.013,223.214 123.593,223.204 124.600 C 223.183 126.555,220.763 132.911,219.410 134.562 C 218.443 135.742,217.876 136.956,217.599 138.440 C 217.041 141.424,215.177 146.434,214.532 146.681 C 214.240 146.794,214.000 147.055,214.000 147.261 C 214.000 147.467,213.550 148.086,213.000 148.636 C 212.450 149.186,212.000 149.893,212.000 150.208 C 212.000 151.386,208.441 154.450,207.597 153.998 C 206.319 153.315,204.913 150.379,204.633 147.811 C 204.365 145.357,202.848 142.147,201.759 141.729 C 200.967 141.425,199.200 137.451,199.200 135.974 C 199.200 134.629,198.435 133.224,196.660 131.311 C 195.363 129.913,194.572 128.123,193.870 125.000 C 193.623 123.900,193.236 122.793,193.010 122.540 C 190.863 120.133,190.147 118.880,188.978 115.481 C 188.100 112.928,187.151 111.003,186.254 109.955 C 185.358 108.908,184.518 107.204,183.847 105.073 C 183.280 103.273,182.497 101.329,182.108 100.753 C 181.719 100.177,180.904 98.997,180.298 98.131 C 179.693 97.265,178.939 95.576,178.624 94.378 C 178.041 92.159,177.125 90.326,175.023 87.168 C 174.375 86.196,173.619 84.539,173.342 83.486 C 172.800 81.429,171.529 79.567,170.131 78.785 C 169.654 78.517,168.697 77.511,168.006 76.549 C 167.316 75.587,166.594 74.800,166.402 74.800 C 166.210 74.800,164.869 73.633,163.421 72.206 C 160.103 68.936,161.107 69.109,146.550 69.301 C 133.437 69.474,128.581 70.162,126.618 72.124 C 126.248 72.495,125.462 72.904,124.872 73.033 C 124.282 73.163,123.088 73.536,122.219 73.863 C 121.349 74.191,119.028 74.638,117.061 74.858 C 113.514 75.254,109.970 76.350,108.782 77.419 C 107.652 78.436,100.146 80.400,97.388 80.400 C 95.775 80.400,93.167 81.360,91.200 82.679 C 90.430 83.195,89.113 83.804,88.274 84.031 C 85.875 84.681,78.799 90.910,74.400 96.243 L 73.400 97.456 73.455 106.028 C 73.526 117.055,74.527 121.238,77.820 124.263 C 78.919 125.273,80.400 127.902,80.400 128.842 C 80.400 129.202,81.075 130.256,81.900 131.186 C 83.563 133.059,85.497 136.346,86.039 138.216 C 86.233 138.886,87.203 140.207,88.196 141.153 C 89.188 142.098,90.000 143.104,90.000 143.388 C 90.000 144.337,92.129 148.594,92.869 149.123 C 93.271 149.410,93.600 149.831,93.600 150.059 C 93.600 150.286,93.932 150.771,94.337 151.136 C 94.743 151.501,95.598 153.004,96.237 154.475 C 96.877 155.947,97.760 157.351,98.200 157.596 C 98.640 157.841,99.900 159.943,101.000 162.267 C 102.207 164.817,103.327 166.644,103.825 166.876 C 104.278 167.087,105.065 168.101,105.573 169.130 C 107.658 173.348,108.097 174.093,110.006 176.647 C 111.103 178.114,112.000 179.725,112.000 180.227 C 112.000 181.048,113.425 183.163,114.678 184.200 C 115.295 184.711,117.396 188.733,117.720 190.022 C 117.855 190.562,118.603 191.633,119.381 192.402 C 120.160 193.171,121.496 195.258,122.351 197.039 C 123.206 198.820,124.167 200.378,124.487 200.501 C 124.807 200.624,125.953 202.496,127.034 204.662 C 128.114 206.828,129.676 209.299,130.505 210.153 C 131.333 211.007,132.124 212.177,132.262 212.753 C 132.618 214.239,134.291 217.048,136.288 219.5
" href="/">YannStatic</a></div><!--<button class="button button--secondary button--circle search-button js-search-toggle"><i class="fas fa-search"></i></button>--><!-- <li><button class="button button--secondary button--circle search-button js-search-toggle"><i class="fas fa-search"></i></button></li> -->
<!-- Champ de recherche -->
<div id="searchbox" class="search search--dark" style="visibility: visible">
<div class="main">
<div class="search__header"></div>
<div class="search-bar">
<div class="search-box js-search-box">
<div class="search-box__icon-search"><i class="fas fa-search"></i></div>
<input id="search-input" type="text" />
<!-- <div class="search-box__icon-clear js-icon-clear">
<a><i class="fas fa-times"></i></a>
</div> -->
</div>
</div>
</div>
</div>
<!-- Script pointing to search-script.js -->
<script>/*!
* Simple-Jekyll-Search
* Copyright 2015-2020, Christian Fei
* Licensed under the MIT License.
*/
(function(){
'use strict'
var _$Templater_7 = {
compile: compile,
setOptions: setOptions
}
const options = {}
options.pattern = /\{(.*?)\}/g
options.template = ''
options.middleware = function () {}
function setOptions (_options) {
options.pattern = _options.pattern || options.pattern
options.template = _options.template || options.template
if (typeof _options.middleware === 'function') {
options.middleware = _options.middleware
}
}
function compile (data) {
return options.template.replace(options.pattern, function (match, prop) {
const value = options.middleware(prop, data[prop], options.template)
if (typeof value !== 'undefined') {
return value
}
return data[prop] || match
})
}
'use strict';
function fuzzysearch (needle, haystack) {
var tlen = haystack.length;
var qlen = needle.length;
if (qlen > tlen) {
return false;
}
if (qlen === tlen) {
return needle === haystack;
}
outer: for (var i = 0, j = 0; i < qlen; i++) {
var nch = needle.charCodeAt(i);
while (j < tlen) {
if (haystack.charCodeAt(j++) === nch) {
continue outer;
}
}
return false;
}
return true;
}
var _$fuzzysearch_1 = fuzzysearch;
'use strict'
/* removed: const _$fuzzysearch_1 = require('fuzzysearch') */;
var _$FuzzySearchStrategy_5 = new FuzzySearchStrategy()
function FuzzySearchStrategy () {
this.matches = function (string, crit) {
return _$fuzzysearch_1(crit.toLowerCase(), string.toLowerCase())
}
}
'use strict'
var _$LiteralSearchStrategy_6 = new LiteralSearchStrategy()
function LiteralSearchStrategy () {
this.matches = function (str, crit) {
if (!str) return false
str = str.trim().toLowerCase()
crit = crit.trim().toLowerCase()
return crit.split(' ').filter(function (word) {
return str.indexOf(word) >= 0
}).length === crit.split(' ').length
}
}
'use strict'
var _$Repository_4 = {
put: put,
clear: clear,
search: search,
setOptions: __setOptions_4
}
/* removed: const _$FuzzySearchStrategy_5 = require('./SearchStrategies/FuzzySearchStrategy') */;
/* removed: const _$LiteralSearchStrategy_6 = require('./SearchStrategies/LiteralSearchStrategy') */;
function NoSort () {
return 0
}
const data = []
let opt = {}
opt.fuzzy = false
opt.limit = 10
opt.searchStrategy = opt.fuzzy ? _$FuzzySearchStrategy_5 : _$LiteralSearchStrategy_6
opt.sort = NoSort
opt.exclude = []
function put (data) {
if (isObject(data)) {
return addObject(data)
}
if (isArray(data)) {
return addArray(data)
}
return undefined
}
function clear () {
data.length = 0
return data
}
function isObject (obj) {
return Boolean(obj) && Object.prototype.toString.call(obj) === '[object Object]'
}
function isArray (obj) {
return Boolean(obj) && Object.prototype.toString.call(obj) === '[object Array]'
}
function addObject (_data) {
data.push(_data)
return data
}
function addArray (_data) {
const added = []
clear()
for (let i = 0, len = _data.length; i < len; i++) {
if (isObject(_data[i])) {
added.push(addObject(_data[i]))
}
}
return added
}
function search (crit) {
if (!crit) {
return []
}
return findMatches(data, crit, opt.searchStrategy, opt).sort(opt.sort)
}
function __setOptions_4 (_opt) {
opt = _opt || {}
opt.fuzzy = _opt.fuzzy || false
opt.limit = _opt.limit || 10
opt.searchStrategy = _opt.fuzzy ? _$FuzzySearchStrategy_5 : _$LiteralSearchStrategy_6
opt.sort = _opt.sort || NoSort
opt.exclude = _opt.exclude || []
}
function findMatches (data, crit, strategy, opt) {
const matches = []
for (let i = 0; i < data.length && matches.length < opt.limit; i++) {
const match = findMatchesInObject(data[i], crit, strategy, opt)
if (match) {
matches.push(match)
}
}
return matches
}
function findMatchesInObject (obj, crit, strategy, opt) {
for (const key in obj) {
if (!isExcluded(obj[key], opt.exclude) && strategy.matches(obj[key], crit)) {
return obj
}
}
}
function isExcluded (term, excludedTerms) {
for (let i = 0, len = excludedTerms.length; i < len; i++) {
const excludedTerm = excludedTerms[i]
if (new RegExp(excludedTerm).test(term)) {
return true
}
}
return false
}
/* globals ActiveXObject:false */
'use strict'
var _$JSONLoader_2 = {
load: load
}
function load (location, callback) {
const xhr = getXHR()
xhr.open('GET', location, true)
xhr.onreadystatechange = createStateChangeListener(xhr, callback)
xhr.send()
}
function createStateChangeListener (xhr, callback) {
return function () {
if (xhr.readyState === 4 && xhr.status === 200) {
try {
callback(null, JSON.parse(xhr.responseText))
} catch (err) {
callback(err, null)
}
}
}
}
function getXHR () {
return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP')
}
'use strict'
var _$OptionsValidator_3 = function OptionsValidator (params) {
if (!validateParams(params)) {
throw new Error('-- OptionsValidator: required options missing')
}
if (!(this instanceof OptionsValidator)) {
return new OptionsValidator(params)
}
const requiredOptions = params.required
this.getRequiredOptions = function () {
return requiredOptions
}
this.validate = function (parameters) {
const errors = []
requiredOptions.forEach(function (requiredOptionName) {
if (typeof parameters[requiredOptionName] === 'undefined') {
errors.push(requiredOptionName)
}
})
return errors
}
function validateParams (params) {
if (!params) {
return false
}
return typeof params.required !== 'undefined' && params.required instanceof Array
}
}
'use strict'
var _$utils_9 = {
merge: merge,
isJSON: isJSON
}
function merge (defaultParams, mergeParams) {
const mergedOptions = {}
for (const option in defaultParams) {
mergedOptions[option] = defaultParams[option]
if (typeof mergeParams[option] !== 'undefined') {
mergedOptions[option] = mergeParams[option]
}
}
return mergedOptions
}
function isJSON (json) {
try {
if (json instanceof Object && JSON.parse(JSON.stringify(json))) {
return true
}
return false
} catch (err) {
return false
}
}
var _$src_8 = {};
(function (window) {
'use strict'
let options = {
searchInput: null,
resultsContainer: null,
json: [],
success: Function.prototype,
searchResultTemplate: '<li><a href="{url}" title="{desc}">{title}</a></li>',
templateMiddleware: Function.prototype,
sortMiddleware: function () {
return 0
},
noResultsText: 'No results found',
limit: 10,
fuzzy: false,
debounceTime: null,
exclude: []
}
let debounceTimerHandle
const debounce = function (func, delayMillis) {
if (delayMillis) {
clearTimeout(debounceTimerHandle)
debounceTimerHandle = setTimeout(func, delayMillis)
} else {
func.call()
}
}
const requiredOptions = ['searchInput', 'resultsContainer', 'json']
/* removed: const _$Templater_7 = require('./Templater') */;
/* removed: const _$Repository_4 = require('./Repository') */;
/* removed: const _$JSONLoader_2 = require('./JSONLoader') */;
const optionsValidator = _$OptionsValidator_3({
required: requiredOptions
})
/* removed: const _$utils_9 = require('./utils') */;
window.SimpleJekyllSearch = function (_options) {
const errors = optionsValidator.validate(_options)
if (errors.length > 0) {
throwError('You must specify the following required options: ' + requiredOptions)
}
options = _$utils_9.merge(options, _options)
_$Templater_7.setOptions({
template: options.searchResultTemplate,
middleware: options.templateMiddleware
})
_$Repository_4.setOptions({
fuzzy: options.fuzzy,
limit: options.limit,
sort: options.sortMiddleware,
exclude: options.exclude
})
if (_$utils_9.isJSON(options.json)) {
initWithJSON(options.json)
} else {
initWithURL(options.json)
}
const rv = {
search: search
}
typeof options.success === 'function' && options.success.call(rv)
return rv
}
function initWithJSON (json) {
_$Repository_4.put(json)
registerInput()
}
function initWithURL (url) {
_$JSONLoader_2.load(url, function (err, json) {
if (err) {
throwError('failed to get JSON (' + url + ')')
}
initWithJSON(json)
})
}
function emptyResultsContainer () {
options.resultsContainer.innerHTML = ''
}
function appendToResultsContainer (text) {
options.resultsContainer.innerHTML += text
}
function registerInput () {
options.searchInput.addEventListener('input', function (e) {
if (isWhitelistedKey(e.which)) {
emptyResultsContainer()
debounce(function () { search(e.target.value) }, options.debounceTime)
}
})
}
function search (query) {
if (isValidQuery(query)) {
emptyResultsContainer()
render(_$Repository_4.search(query), query)
}
}
function render (results, query) {
const len = results.length
if (len === 0) {
return appendToResultsContainer(options.noResultsText)
}
for (let i = 0; i < len; i++) {
results[i].query = query
appendToResultsContainer(_$Templater_7.compile(results[i]))
}
}
function isValidQuery (query) {
return query && query.length > 0
}
function isWhitelistedKey (key) {
return [13, 16, 20, 37, 38, 39, 40, 91].indexOf(key) === -1
}
function throwError (message) {
throw new Error('SimpleJekyllSearch --- ' + message)
}
})(window)
}());
</script>
<!-- Configuration -->
<script>
SimpleJekyllSearch({
searchInput: document.getElementById('search-input'),
resultsContainer: document.getElementById('results-container'),
json: '/search.json',
//searchResultTemplate: '<li><a href="https://static.rnmkcy.eu{url}">{date}&nbsp;{title}</a></li>'
searchResultTemplate: '<li><a href="{url}">{date}&nbsp;{title}</a></li>'
})
</script>
<!-- Fin déclaration champ de recherche --></div><nav class="navigation">
<ul><li class="navigation__item"><a href="/archive.html">Etiquettes</a></li><li class="navigation__item"><a href="/htmldoc.html">Documents</a></li><li class="navigation__item"><a href="/liens_ttrss.html">Liens</a></li><li class="navigation__item"><a href="/aide-jekyll-text-theme.html">Aide</a></li></ul>
</nav></div>
</header>
</div><div class="page__content"><div class ="main"><div class="grid grid--reverse">
<div class="col-main cell cell--auto"><!-- start custom main top snippet --><div id="results-container" class="search-result js-search-result"></div><!-- end custom main top snippet -->
<article itemscope itemtype="http://schema.org/Article"><div class="article__header"><header><h1 style="color:Tomato;">ngx_lua</h1></header></div><meta itemprop="headline" content="ngx_lua"><div class="article__info clearfix"><ul class="left-col menu"><li>
<a class="button button--secondary button--pill button--sm"
href="/archive.html?tag=lua">lua</a>
</li></ul><ul class="right-col menu"><li>
<i class="far fa-calendar-alt"></i>&nbsp;<span title="Création" style="color:#FF00FF">25&nbsp;déc.&nbsp;&nbsp;2019</span>
<span title="Modification" style="color:#00FF7F">23&nbsp;nov.&nbsp;&nbsp;2018</span></li></ul></div><meta itemprop="datePublished" content="2018-11-23T00:00:00+01:00">
<meta itemprop="keywords" content="lua"><div class="js-article-content">
<div class="layout--article"><!-- start custom article top snippet -->
<style>
#myBtn {
display: none;
position: fixed;
bottom: 10px;
right: 10px;
z-index: 99;
font-size: 12px;
font-weight: bold;
border: none;
outline: none;
background-color: white;
color: black;
cursor: pointer;
padding: 5px;
border-radius: 4px;
}
#myBtn:hover {
background-color: #555;
}
</style>
<button onclick="topFunction()" id="myBtn" title="Haut de page">&#8679;</button>
<script>
//Get the button
var mybutton = document.getElementById("myBtn");
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
</script>
<!-- end custom article top snippet -->
<div class="article__content" itemprop="articleBody"><details>
<summary><b>Afficher/cacher Sommaire</b></summary>
<!-- affichage sommaire -->
<div class="toc-aside js-toc-root"></div>
</details><h1 id="name">Name</h1>
<p>ngx_lua - Embed the power of Lua into Nginx</p>
<p><em>This module is not distributed with the Nginx source.</em> See <a href="#installation">the installation instructions</a>.</p>
<h1 id="table-of-contents">Table of Contents</h1>
<ul>
<li><a href="#name">Name</a></li>
<li><a href="#status">Status</a></li>
<li><a href="#version">Version</a></li>
<li><a href="#synopsis">Synopsis</a></li>
<li><a href="#description">Description</a></li>
<li><a href="#typical-uses">Typical Uses</a></li>
<li><a href="#nginx-compatibility">Nginx Compatibility</a></li>
<li><a href="#installation">Installation</a>
<ul>
<li><a href="#c-macro-configurations">C Macro Configurations</a></li>
<li><a href="#installation-on-ubuntu-1110">Installation on Ubuntu 11.10</a></li>
</ul>
</li>
<li><a href="#community">Community</a>
<ul>
<li><a href="#english-mailing-list">English Mailing List</a></li>
<li><a href="#chinese-mailing-list">Chinese Mailing List</a></li>
</ul>
</li>
<li><a href="#code-repository">Code Repository</a></li>
<li><a href="#bugs-and-patches">Bugs and Patches</a></li>
<li><a href="#lualuajit-bytecode-support">Lua/LuaJIT bytecode support</a></li>
<li><a href="#system-environment-variable-support">System Environment Variable Support</a></li>
<li><a href="#http-10-support">HTTP 1.0 support</a></li>
<li><a href="#statically-linking-pure-lua-modules">Statically Linking Pure Lua Modules</a></li>
<li><a href="#data-sharing-within-an-nginx-worker">Data Sharing within an Nginx Worker</a></li>
<li><a href="#known-issues">Known Issues</a>
<ul>
<li><a href="#tcp-socket-connect-operation-issues">TCP socket connect operation issues</a></li>
<li><a href="#lua-coroutine-yieldingresuming">Lua Coroutine Yielding/Resuming</a></li>
<li><a href="#lua-variable-scope">Lua Variable Scope</a></li>
<li><a href="#locations-configured-by-subrequest-directives-of-other-modules">Locations Configured by Subrequest Directives of Other Modules</a></li>
<li><a href="#cosockets-not-available-everywhere">Cosockets Not Available Everywhere</a></li>
<li><a href="#special-escaping-sequences">Special Escaping Sequences</a></li>
<li><a href="#mixing-with-ssi-not-supported">Mixing with SSI Not Supported</a></li>
<li><a href="#spdy-mode-not-fully-supported">SPDY Mode Not Fully Supported</a></li>
<li><a href="#missing-data-on-short-circuited-requests">Missing data on short circuited requests</a></li>
</ul>
</li>
<li><a href="#todo">TODO</a></li>
<li><a href="#changes">Changes</a></li>
<li><a href="#test-suite">Test Suite</a></li>
<li><a href="#copyright-and-license">Copyright and License</a></li>
<li><a href="#see-also">See Also</a></li>
<li><a href="#directives">Directives</a></li>
<li><a href="#nginx-api-for-lua">Nginx API for Lua</a></li>
<li><a href="#obsolete-sections">Obsolete Sections</a>
<ul>
<li><a href="#special-pcre-sequences">Special PCRE Sequences</a></li>
</ul>
</li>
</ul>
<h1 id="status">Status</h1>
<p>Production ready.</p>
<h1 id="version">Version</h1>
<p>This document describes ngx_lua <a href="https://github.com/openresty/lua-nginx-module/tags">v0.9.16</a> released on 22 June 2015.</p>
<h1 id="synopsis">Synopsis</h1>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="c1"># set search paths for pure Lua external libraries (';;' is the default path):</span>
<span class="k">lua_package_path</span> <span class="s">'/foo/bar/?.lua</span><span class="p">;</span><span class="k">/blah/?.lua</span><span class="p">;</span>;<span class="k">'</span><span class="p">;</span>
<span class="c1"># set search paths for Lua external libraries written in C (can also use ';;'):</span>
<span class="k">lua_package_cpath</span> <span class="s">'/bar/baz/?.so</span><span class="p">;</span><span class="k">/blah/blah/?.so</span><span class="p">;</span>;<span class="k">'</span><span class="p">;</span>
<span class="k">server</span> <span class="p">{</span>
<span class="kn">location</span> <span class="n">/inline_concat</span> <span class="p">{</span>
<span class="c1"># MIME type determined by default_type:</span>
<span class="kn">default_type</span> <span class="s">'text/plain'</span><span class="p">;</span>
<span class="kn">set</span> <span class="nv">$a</span> <span class="s">"hello"</span><span class="p">;</span>
<span class="kn">set</span> <span class="nv">$b</span> <span class="s">"world"</span><span class="p">;</span>
<span class="c1"># inline Lua script</span>
<span class="kn">set_by_lua</span> <span class="nv">$res</span> <span class="s">"return</span> <span class="s">ngx.arg[1]..ngx.arg[2]"</span> <span class="nv">$a</span> <span class="nv">$b</span><span class="p">;</span>
<span class="kn">echo</span> <span class="nv">$res</span><span class="p">;</span>
<span class="p">}</span>
<span class="kn">location</span> <span class="n">/rel_file_concat</span> <span class="p">{</span>
<span class="kn">set</span> <span class="nv">$a</span> <span class="s">"foo"</span><span class="p">;</span>
<span class="kn">set</span> <span class="nv">$b</span> <span class="s">"bar"</span><span class="p">;</span>
<span class="c1"># script path relative to nginx prefix</span>
<span class="c1"># $ngx_prefix/conf/concat.lua contents:</span>
<span class="c1">#</span>
<span class="c1"># return ngx.arg[1]..ngx.arg[2]</span>
<span class="c1">#</span>
<span class="kn">set_by_lua_file</span> <span class="nv">$res</span> <span class="nc">conf/concat</span><span class="s">.lua</span> <span class="nv">$a</span> <span class="nv">$b</span><span class="p">;</span>
<span class="kn">echo</span> <span class="nv">$res</span><span class="p">;</span>
<span class="p">}</span>
<span class="kn">location</span> <span class="n">/abs_file_concat</span> <span class="p">{</span>
<span class="kn">set</span> <span class="nv">$a</span> <span class="s">"fee"</span><span class="p">;</span>
<span class="kn">set</span> <span class="nv">$b</span> <span class="s">"baz"</span><span class="p">;</span>
<span class="c1"># absolute script path not modified</span>
<span class="kn">set_by_lua_file</span> <span class="nv">$res</span> <span class="n">/usr/nginx/conf/concat.lua</span> <span class="nv">$a</span> <span class="nv">$b</span><span class="p">;</span>
<span class="kn">echo</span> <span class="nv">$res</span><span class="p">;</span>
<span class="p">}</span>
<span class="kn">location</span> <span class="n">/lua_content</span> <span class="p">{</span>
<span class="c1"># MIME type determined by default_type:</span>
<span class="kn">default_type</span> <span class="s">'text/plain'</span><span class="p">;</span>
<span class="kn">content_by_lua</span> <span class="s">"ngx.say('Hello,world!')"</span><span class="p">;</span>
<span class="p">}</span>
<span class="kn">location</span> <span class="n">/nginx_var</span> <span class="p">{</span>
<span class="c1"># MIME type determined by default_type:</span>
<span class="kn">default_type</span> <span class="s">'text/plain'</span><span class="p">;</span>
<span class="c1"># try access /nginx_var?a=hello,world</span>
<span class="kn">content_by_lua</span> <span class="s">"ngx.print(ngx.var['arg_a'],</span> <span class="s">'</span><span class="err">\\</span><span class="s">n')"</span><span class="p">;</span>
<span class="p">}</span>
<span class="kn">location</span> <span class="n">/request_body</span> <span class="p">{</span>
<span class="c1"># force reading request body (default off)</span>
<span class="kn">lua_need_request_body</span> <span class="no">on</span><span class="p">;</span>
<span class="kn">client_max_body_size</span> <span class="mi">50k</span><span class="p">;</span>
<span class="kn">client_body_buffer_size</span> <span class="mi">50k</span><span class="p">;</span>
<span class="kn">content_by_lua</span> <span class="s">'ngx.print(ngx.var.request_body)'</span><span class="p">;</span>
<span class="p">}</span>
<span class="c1"># transparent non-blocking I/O in Lua via subrequests</span>
<span class="kn">location</span> <span class="n">/lua</span> <span class="p">{</span>
<span class="c1"># MIME type determined by default_type:</span>
<span class="kn">default_type</span> <span class="s">'text/plain'</span><span class="p">;</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">res</span> <span class="p">=</span> <span class="s">ngx.location.capture("/some_other_location")</span>
<span class="s">if</span> <span class="s">res.status</span> <span class="p">==</span> <span class="mi">200</span> <span class="s">then</span>
<span class="s">ngx.print(res.body)</span>
<span class="s">end'</span><span class="p">;</span>
<span class="p">}</span>
<span class="c1"># GET /recur?num=5</span>
<span class="kn">location</span> <span class="n">/recur</span> <span class="p">{</span>
<span class="c1"># MIME type determined by default_type:</span>
<span class="kn">default_type</span> <span class="s">'text/plain'</span><span class="p">;</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">num</span> <span class="p">=</span> <span class="s">tonumber(ngx.var.arg_num)</span> <span class="s">or</span> <span class="mi">0</span>
<span class="s">if</span> <span class="s">num</span> <span class="s">&gt;</span> <span class="mi">50</span> <span class="s">then</span>
<span class="s">ngx.say("num</span> <span class="s">too</span> <span class="s">big")</span>
<span class="s">return</span>
<span class="s">end</span>
<span class="s">ngx.say("num</span> <span class="s">is:</span> <span class="s">",</span> <span class="s">num)</span>
<span class="s">if</span> <span class="s">num</span> <span class="s">&gt;</span> <span class="mi">0</span> <span class="s">then</span>
<span class="s">res</span> <span class="p">=</span> <span class="s">ngx.location.capture("/recur?num="</span> <span class="s">..</span> <span class="s">tostring(num</span> <span class="s">-</span> <span class="mi">1</span><span class="s">))</span>
<span class="s">ngx.print("status=",</span> <span class="s">res.status,</span> <span class="s">"</span> <span class="s">")</span>
<span class="s">ngx.print("body=",</span> <span class="s">res.body)</span>
<span class="s">else</span>
<span class="s">ngx.say("end")</span>
<span class="s">end</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="kn">location</span> <span class="n">/foo</span> <span class="p">{</span>
<span class="kn">rewrite_by_lua</span> <span class="s">'</span>
<span class="s">res</span> <span class="p">=</span> <span class="s">ngx.location.capture("/memc",</span>
<span class="p">{</span> <span class="kn">args</span> <span class="p">=</span> <span class="p">{</span> <span class="kn">cmd</span> <span class="p">=</span> <span class="s">"incr",</span> <span class="s">key</span> <span class="p">=</span> <span class="s">ngx.var.uri</span> <span class="err">}</span> <span class="err">}</span>
<span class="s">)</span>
<span class="s">'</span><span class="p">;</span>
<span class="kn">proxy_pass</span> <span class="s">http://blah.blah.com</span><span class="p">;</span>
<span class="p">}</span>
<span class="kn">location</span> <span class="n">/blah</span> <span class="p">{</span>
<span class="kn">access_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">res</span> <span class="p">=</span> <span class="s">ngx.location.capture("/auth")</span>
<span class="s">if</span> <span class="s">res.status</span> <span class="p">==</span> <span class="s">ngx.HTTP_OK</span> <span class="s">then</span>
<span class="s">return</span>
<span class="s">end</span>
<span class="s">if</span> <span class="s">res.status</span> <span class="p">==</span> <span class="s">ngx.HTTP_FORBIDDEN</span> <span class="s">then</span>
<span class="s">ngx.exit(res.status)</span>
<span class="s">end</span>
<span class="s">ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)</span>
<span class="s">'</span><span class="p">;</span>
<span class="c1"># proxy_pass/fastcgi_pass/postgres_pass/...</span>
<span class="p">}</span>
<span class="kn">location</span> <span class="n">/mixed</span> <span class="p">{</span>
<span class="kn">rewrite_by_lua_file</span> <span class="n">/path/to/rewrite.lua</span><span class="p">;</span>
<span class="kn">access_by_lua_file</span> <span class="n">/path/to/access.lua</span><span class="p">;</span>
<span class="kn">content_by_lua_file</span> <span class="n">/path/to/content.lua</span><span class="p">;</span>
<span class="p">}</span>
<span class="c1"># use nginx var in code path</span>
<span class="c1"># WARNING: contents in nginx var must be carefully filtered,</span>
<span class="c1"># otherwise there'll be great security risk!</span>
<span class="kn">location</span> <span class="p">~</span> <span class="sr">^/app/([-_a-zA-Z0-9/]+)</span> <span class="p">{</span>
<span class="kn">set</span> <span class="nv">$path</span> <span class="nv">$1</span><span class="p">;</span>
<span class="kn">content_by_lua_file</span> <span class="n">/path/to/lua/app/root/</span><span class="nv">$path</span><span class="s">.lua</span><span class="p">;</span>
<span class="p">}</span>
<span class="kn">location</span> <span class="n">/</span> <span class="p">{</span>
<span class="kn">lua_need_request_body</span> <span class="no">on</span><span class="p">;</span>
<span class="kn">client_max_body_size</span> <span class="mi">100k</span><span class="p">;</span>
<span class="kn">client_body_buffer_size</span> <span class="mi">100k</span><span class="p">;</span>
<span class="kn">access_by_lua</span> <span class="s">'</span>
<span class="s">--</span> <span class="s">check</span> <span class="s">the</span> <span class="s">client</span> <span class="s">IP</span> <span class="s">address</span> <span class="s">is</span> <span class="s">in</span> <span class="s">our</span> <span class="s">black</span> <span class="s">list</span>
<span class="s">if</span> <span class="s">ngx.var.remote_addr</span> <span class="p">==</span> <span class="s">"132.5.72.3"</span> <span class="s">then</span>
<span class="s">ngx.exit(ngx.HTTP_FORBIDDEN)</span>
<span class="s">end</span>
<span class="s">--</span> <span class="s">check</span> <span class="s">if</span> <span class="s">the</span> <span class="s">request</span> <span class="s">body</span> <span class="s">contains</span> <span class="s">bad</span> <span class="s">words</span>
<span class="s">if</span> <span class="s">ngx.var.request_body</span> <span class="s">and</span>
<span class="s">string.match(ngx.var.request_body,</span> <span class="s">"fsck")</span>
<span class="s">then</span>
<span class="s">return</span> <span class="s">ngx.redirect("/terms_of_use.html")</span>
<span class="s">end</span>
<span class="s">--</span> <span class="s">tests</span> <span class="s">passed</span>
<span class="s">'</span><span class="p">;</span>
<span class="c1"># proxy_pass/fastcgi_pass/etc settings</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="description">Description</h1>
<p>This module embeds Lua, via the standard Lua 5.1 interpreter or <a href="http://luajit.org/luajit.html">LuaJIT 2.0/2.1</a>, into Nginx and by leveraging Nginxs subrequests, allows the integration of the powerful Lua threads (Lua coroutines) into the Nginx event model.</p>
<p>Unlike <a href="https://httpd.apache.org/docs/trunk/mod/mod_lua.html">Apaches mod_lua</a> and <a href="http://redmine.lighttpd.net/wiki/1/Docs:ModMagnet">Lighttpds mod_magnet</a>, Lua code executed using this module can be <em>100% non-blocking</em> on network traffic as long as the <a href="#nginx-api-for-lua">Nginx API for Lua</a> provided by this module is used to handle
requests to upstream services such as MySQL, PostgreSQL, Memcached, Redis, or upstream HTTP web services.</p>
<p>At least the following Lua libraries and Nginx modules can be used with this ngx_lua module:</p>
<ul>
<li><a href="https://github.com/openresty/lua-resty-memcached">lua-resty-memcached</a></li>
<li><a href="https://github.com/openresty/lua-resty-mysql">lua-resty-mysql</a></li>
<li><a href="https://github.com/openresty/lua-resty-redis">lua-resty-redis</a></li>
<li><a href="https://github.com/openresty/lua-resty-dns">lua-resty-dns</a></li>
<li><a href="https://github.com/openresty/lua-resty-upload">lua-resty-upload</a></li>
<li><a href="https://github.com/openresty/lua-resty-websocket">lua-resty-websocket</a></li>
<li><a href="https://github.com/openresty/lua-resty-lock">lua-resty-lock</a></li>
<li><a href="https://github.com/cloudflare/lua-resty-logger-socket">lua-resty-logger-socket</a></li>
<li><a href="https://github.com/openresty/lua-resty-lrucache">lua-resty-lrucache</a></li>
<li><a href="https://github.com/openresty/lua-resty-string">lua-resty-string</a></li>
<li><a href="http://github.com/openresty/memc-nginx-module">ngx_memc</a></li>
<li><a href="https://github.com/FRiCKLE/ngx_postgres">ngx_postgres</a></li>
<li><a href="http://github.com/openresty/redis2-nginx-module">ngx_redis2</a></li>
<li><a href="http://wiki.nginx.org/HttpRedisModule">ngx_redis</a></li>
<li><a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html">ngx_proxy</a></li>
<li><a href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html">ngx_fastcgi</a></li>
</ul>
<p>Almost all the Nginx modules can be used with this ngx_lua module by means of <a href="#ngxlocationcapture">ngx.location.capture</a> or <a href="#ngxlocationcapture_multi">ngx.location.capture_multi</a> but it is recommended to use those <code class="language-plaintext highlighter-rouge">lua-resty-*</code> libraries instead of creating subrequests to access the Nginx upstream modules because the former is usually much more flexible and memory-efficient.</p>
<p>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.</p>
<p>Loaded Lua modules persist in the nginx worker process level resulting in a small memory footprint in Lua even when under heavy loads.</p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="typical-uses">Typical Uses</h1>
<p>Just to name a few:</p>
<ul>
<li>Mashuping and processing outputs of various nginx upstream outputs (proxy, drizzle, postgres, redis, memcached, and etc) in Lua,</li>
<li>doing arbitrarily complex access control and security checks in Lua before requests actually reach the upstream backends,</li>
<li>manipulating response headers in an arbitrary way (by Lua)</li>
<li>fetching backend information from external storage backends (like redis, memcached, mysql, postgresql) and use that information to choose which upstream backend to access on-the-fly,</li>
<li>coding up arbitrarily complex web applications in a content handler using synchronous but still non-blocking access to the database backends and other storage,</li>
<li>doing very complex URL dispatch in Lua at rewrite phase,</li>
<li>using Lua to implement advanced caching mechanism for Nginxs subrequests and arbitrary locations.</li>
</ul>
<p>The possibilities are unlimited as the module allows bringing together various elements within Nginx as well as exposing the power of the Lua language to the user. The module provides the full flexibility of scripting while offering performance levels comparable with native C language programs both in terms of CPU time as well as memory footprint. This is particularly the case when LuaJIT 2.x is enabled.</p>
<p>Other scripting language implementations typically struggle to match this performance level.</p>
<p>The Lua state (Lua VM instance) is shared across all the requests handled by a single nginx worker process to minimize memory use.</p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="nginx-compatibility">Nginx Compatibility</h1>
<p>The latest module is compatible with the following versions of Nginx:</p>
<ul>
<li>1.7.x (last tested: 1.7.10)</li>
<li>1.6.x</li>
<li>1.5.x (last tested: 1.5.12)</li>
<li>1.4.x (last tested: 1.4.4)</li>
<li>1.3.x (last tested: 1.3.11)</li>
<li>1.2.x (last tested: 1.2.9)</li>
<li>1.1.x (last tested: 1.1.5)</li>
<li>1.0.x (last tested: 1.0.15)</li>
<li>0.9.x (last tested: 0.9.4)</li>
<li>0.8.x &gt;= 0.8.54 (last tested: 0.8.54)</li>
</ul>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="installation">Installation</h1>
<p>It is highly recommended to use the <a href="http://openresty.org">ngx_openresty bundle</a> that bundles Nginx, ngx_lua, LuaJIT 2.0/2.1 (or the optional standard Lua 5.1 interpreter), as well as a package of powerful companion Nginx modules. The basic installation step is a simple command: <code class="language-plaintext highlighter-rouge">./configure --with-luajit &amp;&amp; make &amp;&amp; make install</code>.</p>
<p>Alternatively, ngx_lua can be manually compiled into Nginx:</p>
<ol>
<li>Install LuaJIT 2.0 or 2.1 (recommended) or Lua 5.1 (Lua 5.2 is <em>not</em> supported yet). LuaJIT can be downloaded from the <a href="http://luajit.org/download.html">the LuaJIT project website</a> and Lua 5.1, from the <a href="http://www.lua.org/">Lua project website</a>. Some distribution package managers also distribute LuajIT and/or Lua.</li>
<li>Download the latest version of the ngx_devel_kit (NDK) module <a href="https://github.com/simpl/ngx_devel_kit/tags">HERE</a>.</li>
<li>Download the latest version of ngx_lua <a href="https://github.com/openresty/lua-nginx-module/tags">HERE</a>.</li>
<li>Download the latest version of Nginx <a href="http://nginx.org/">HERE</a> (See <a href="#nginx-compatibility">Nginx Compatibility</a>)</li>
</ol>
<p>Build the source with this module:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
wget <span class="s1">'http://nginx.org/download/nginx-1.7.10.tar.gz'</span>
<span class="nb">tar</span> <span class="nt">-xzvf</span> nginx-1.7.10.tar.gz
<span class="nb">cd </span>nginx-1.7.10/
<span class="c"># tell nginx's build system where to find LuaJIT 2.0:</span>
<span class="nb">export </span><span class="nv">LUAJIT_LIB</span><span class="o">=</span>/path/to/luajit/lib
<span class="nb">export </span><span class="nv">LUAJIT_INC</span><span class="o">=</span>/path/to/luajit/include/luajit-2.0
<span class="c"># tell nginx's build system where to find LuaJIT 2.1:</span>
<span class="nb">export </span><span class="nv">LUAJIT_LIB</span><span class="o">=</span>/path/to/luajit/lib
<span class="nb">export </span><span class="nv">LUAJIT_INC</span><span class="o">=</span>/path/to/luajit/include/luajit-2.1
<span class="c"># or tell where to find Lua if using Lua instead:</span>
<span class="c">#export LUA_LIB=/path/to/lua/lib</span>
<span class="c">#export LUA_INC=/path/to/lua/include</span>
<span class="c"># Here we assume Nginx is to be installed under /opt/nginx/.</span>
./configure <span class="nt">--prefix</span><span class="o">=</span>/opt/nginx <span class="se">\</span>
<span class="nt">--with-ld-opt</span><span class="o">=</span><span class="s2">"-Wl,-rpath,/path/to/luajit-or-lua/lib"</span> <span class="se">\</span>
<span class="nt">--add-module</span><span class="o">=</span>/path/to/ngx_devel_kit <span class="se">\</span>
<span class="nt">--add-module</span><span class="o">=</span>/path/to/lua-nginx-module
make <span class="nt">-j2</span>
make <span class="nb">install</span>
</code></pre></div></div>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h2 id="c-macro-configurations">C Macro Configurations</h2>
<p>While building this module either via OpenResty or with the NGINX core, you can define the following C macros via the C compiler options:</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">NGX_LUA_USE_ASSERT</code>
When defined, will enable assertions in the ngx_lua C code base. Recommended for debugging or testing builds. It can introduce some (small) runtime overhead when enabled. This macro was first introduced in the <code class="language-plaintext highlighter-rouge">v0.9.10</code> release.</li>
<li><code class="language-plaintext highlighter-rouge">NGX_LUA_ABORT_AT_PANIC</code>
When the Lua/LuaJIT VM panics, ngx_lua will instruct the current nginx worker process to quit gracefully by default. By specifying this C macro, ngx_lua will abort the current nginx worker process (which usually result in a core dump file) immediately. This option is useful for debugging VM panics. This option was first introduced in the <code class="language-plaintext highlighter-rouge">v0.9.8</code> release.</li>
<li><code class="language-plaintext highlighter-rouge">NGX_LUA_NO_FFI_API</code>
Excludes pure C API functions for FFI-based Lua API for NGINX (as required by <a href="https://github.com/openresty/lua-resty-core#readme">lua-resty-core</a>, for example). Enabling this macro can make the resulting binary code size smaller.</li>
</ul>
<p>To enable one or more of these macros, just pass extra C compiler options to the <code class="language-plaintext highlighter-rouge">./configure</code> script of either NGINX or OpenResty. For instance,</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>./configure --with-cc-opt="-DNGX_LUA_USE_ASSERT -DNGX_LUA_ABORT_AT_PANIC"
</code></pre></div></div>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h2 id="installation-on-ubuntu-1110">Installation on Ubuntu 11.10</h2>
<p>Note that it is recommended to use LuaJIT 2.0 or LuaJIT 2.1 instead of the standard Lua 5.1 interpreter wherever possible.</p>
<p>If the standard Lua 5.1 interpreter is required however, run the following command to install it from the Ubuntu repository:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
apt-get <span class="nb">install</span> <span class="nt">-y</span> lua5.1 liblua5.1-0 liblua5.1-0-dev
</code></pre></div></div>
<p>Everything should be installed correctly, except for one small tweak.</p>
<p>Library name <code class="language-plaintext highlighter-rouge">liblua.so</code> has been changed in liblua5.1 package, it only comes with <code class="language-plaintext highlighter-rouge">liblua5.1.so</code>, which needs to be symlinked to <code class="language-plaintext highlighter-rouge">/usr/lib</code> so it could be found during the configuration process.</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="nb">ln</span> <span class="nt">-s</span> /usr/lib/x86_64-linux-gnu/liblua5.1.so /usr/lib/liblua.so
</code></pre></div></div>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="community">Community</h1>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h2 id="english-mailing-list">English Mailing List</h2>
<p>The <a href="https://groups.google.com/group/openresty-en">openresty-en</a> mailing list is for English speakers.</p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h2 id="chinese-mailing-list">Chinese Mailing List</h2>
<p>The <a href="https://groups.google.com/group/openresty">openresty</a> mailing list is for Chinese speakers.</p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="code-repository">Code Repository</h1>
<p>The code repository of this project is hosted on github at <a href="https://github.com/openresty/lua-nginx-module">openresty/lua-nginx-module</a>.</p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="bugs-and-patches">Bugs and Patches</h1>
<p>Please submit bug reports, wishlists, or patches by</p>
<ol>
<li>creating a ticket on the <a href="https://github.com/openresty/lua-nginx-module/issues">GitHub Issue Tracker</a>,</li>
<li>or posting to the <a href="#community">OpenResty community</a>.</li>
</ol>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="lualuajit-bytecode-support">Lua/LuaJIT bytecode support</h1>
<p>As from the <code class="language-plaintext highlighter-rouge">v0.5.0rc32</code> release, all <code class="language-plaintext highlighter-rouge">*_by_lua_file</code> configure directives (such as <a href="#content_by_lua_file">content_by_lua_file</a>) support loading Lua 5.1 and LuaJIT 2.0/2.1 raw bytecode files directly.</p>
<p>Please note that the bytecode format used by LuaJIT 2.0/2.1 is not compatible with that used by the standard Lua 5.1 interpreter. So if using LuaJIT 2.0/2.1 with ngx_lua, LuaJIT compatible bytecode files must be generated as shown:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
/path/to/luajit/bin/luajit <span class="nt">-b</span> /path/to/input_file.lua /path/to/output_file.luac
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">-bg</code> option can be used to include debug information in the LuaJIT bytecode file:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
/path/to/luajit/bin/luajit <span class="nt">-bg</span> /path/to/input_file.lua /path/to/output_file.luac
</code></pre></div></div>
<p>Please refer to the official LuaJIT documentation on the <code class="language-plaintext highlighter-rouge">-b</code> option for more details:</p>
<p><a href="http://luajit.org/running.html#opt_b">http://luajit.org/running.html#opt_b</a></p>
<p>Also, the bytecode files generated by LuaJIT 2.1 is <em>not</em> compatible with LuaJIT 2.0, and vice versa. The support for LuaJIT 2.1 bytecode was first added in ngx_lua v0.9.3.</p>
<p>Similarly, if using the standard Lua 5.1 interpreter with ngx_lua, Lua compatible bytecode files must be generated using the <code class="language-plaintext highlighter-rouge">luac</code> commandline utility as shown:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
luac <span class="nt">-o</span> /path/to/output_file.luac /path/to/input_file.lua
</code></pre></div></div>
<p>Unlike as with LuaJIT, debug information is included in standard Lua 5.1 bytecode files by default. This can be striped out by specifying the <code class="language-plaintext highlighter-rouge">-s</code> option as shown:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
luac <span class="nt">-s</span> <span class="nt">-o</span> /path/to/output_file.luac /path/to/input_file.lua
</code></pre></div></div>
<p>Attempts to load standard Lua 5.1 bytecode files into ngx_lua instances linked to LuaJIT 2.0/2.1 or vice versa, will result in an error message, such as that below, being logged into the Nginx <code class="language-plaintext highlighter-rouge">error.log</code> file:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[error] 13909#0: *1 failed to load Lua inlined code: bad byte-code header in /path/to/test_file.luac
</code></pre></div></div>
<p>Loading bytecode files via the Lua primitives like <code class="language-plaintext highlighter-rouge">require</code> and <code class="language-plaintext highlighter-rouge">dofile</code> should always work as expected.</p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="system-environment-variable-support">System Environment Variable Support</h1>
<p>If you want to access the system environment variable, say, <code class="language-plaintext highlighter-rouge">foo</code>, in Lua via the standard Lua API <a href="http://www.lua.org/manual/5.1/manual.html#pdf-os.getenv">os.getenv</a>, then you should also list this environment variable name in your <code class="language-plaintext highlighter-rouge">nginx.conf</code> file via the <a href="http://nginx.org/en/docs/ngx_core_module.html#env">env directive</a>. For example,</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">env</span> <span class="s">foo</span><span class="p">;</span>
</code></pre></div></div>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="http-10-support">HTTP 1.0 support</h1>
<p>The HTTP 1.0 protocol does not support chunked output and requires an explicit <code class="language-plaintext highlighter-rouge">Content-Length</code> header when the response body is not empty in order to support the HTTP 1.0 keep-alive.
So when a HTTP 1.0 request is made and the <a href="#lua_http10_buffering">lua_http10_buffering</a> directive is turned <code class="language-plaintext highlighter-rouge">on</code>, ngx_lua will buffer the
output of <a href="#ngxsay">ngx.say</a> and <a href="#ngxprint">ngx.print</a> calls and also postpone sending response headers until all the response body output is received.
At that time ngx_lua can calculate the total length of the body and construct a proper <code class="language-plaintext highlighter-rouge">Content-Length</code> header to return to the HTTP 1.0 client.
If the <code class="language-plaintext highlighter-rouge">Content-Length</code> response header is set in the running Lua code, however, this buffering will be disabled even if the <a href="#lua_http10_buffering">lua_http10_buffering</a> directive is turned <code class="language-plaintext highlighter-rouge">on</code>.</p>
<p>For large streaming output responses, it is important to disable the <a href="#lua_http10_buffering">lua_http10_buffering</a> directive to minimise memory usage.</p>
<p>Note that common HTTP benchmark tools such as <code class="language-plaintext highlighter-rouge">ab</code> and <code class="language-plaintext highlighter-rouge">http_load</code> issue HTTP 1.0 requests by default.
To force <code class="language-plaintext highlighter-rouge">curl</code> to send HTTP 1.0 requests, use the <code class="language-plaintext highlighter-rouge">-0</code> option.</p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="statically-linking-pure-lua-modules">Statically Linking Pure Lua Modules</h1>
<p>When LuaJIT 2.x is used, it is possible to statically link the bytecode of pure Lua modules into the Nginx executable.</p>
<p>Basically you use the <code class="language-plaintext highlighter-rouge">luajit</code> executable to compile <code class="language-plaintext highlighter-rouge">.lua</code> Lua module files to <code class="language-plaintext highlighter-rouge">.o</code> object files containing the exported bytecode data, and then link the <code class="language-plaintext highlighter-rouge">.o</code> files directly in your Nginx build.</p>
<p>Below is a trivial example to demonstrate this. Consider that we have the following <code class="language-plaintext highlighter-rouge">.lua</code> file named <code class="language-plaintext highlighter-rouge">foo.lua</code>:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="c1">-- foo.lua</span>
<span class="kd">local</span> <span class="n">_M</span> <span class="o">=</span> <span class="p">{}</span>
<span class="k">function</span> <span class="nc">_M</span><span class="p">.</span><span class="nf">go</span><span class="p">()</span>
<span class="nb">print</span><span class="p">(</span><span class="s2">"Hello from foo"</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">return</span> <span class="n">_M</span>
</code></pre></div></div>
<p>And then we compile this <code class="language-plaintext highlighter-rouge">.lua</code> file to <code class="language-plaintext highlighter-rouge">foo.o</code> file:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/path/to/luajit/bin/luajit -bg foo.lua foo.o
</code></pre></div></div>
<p>What matters here is the name of the <code class="language-plaintext highlighter-rouge">.lua</code> file, which determines how you use this module later on the Lua land. The file name <code class="language-plaintext highlighter-rouge">foo.o</code> does not matter at all except the <code class="language-plaintext highlighter-rouge">.o</code> file extension (which tells <code class="language-plaintext highlighter-rouge">luajit</code> what output format is used). If you want to strip the Lua debug information from the resulting bytecode, you can just specify the <code class="language-plaintext highlighter-rouge">-b</code> option above instead of <code class="language-plaintext highlighter-rouge">-bg</code>.</p>
<p>Then when building Nginx or OpenResty, pass the <code class="language-plaintext highlighter-rouge">--with-ld-opt="foo.o"</code> option to the <code class="language-plaintext highlighter-rouge">./configure</code> script:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
./configure <span class="nt">--with-ld-opt</span><span class="o">=</span><span class="s2">"/path/to/foo.o"</span> ...
</code></pre></div></div>
<p>Finally, you can just do the following in any Lua code run by ngx_lua:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">foo</span> <span class="o">=</span> <span class="nb">require</span> <span class="s2">"foo"</span>
<span class="n">foo</span><span class="p">.</span><span class="n">go</span><span class="p">()</span>
</code></pre></div></div>
<p>And this piece of code no longer depends on the external <code class="language-plaintext highlighter-rouge">foo.lua</code> file any more because it has already been compiled into the <code class="language-plaintext highlighter-rouge">nginx</code> executable.</p>
<p>If you want to use dot in the Lua module name when calling <code class="language-plaintext highlighter-rouge">require</code>, as in</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">foo</span> <span class="o">=</span> <span class="nb">require</span> <span class="s2">"resty.foo"</span>
</code></pre></div></div>
<p>then you need to rename the <code class="language-plaintext highlighter-rouge">foo.lua</code> file to <code class="language-plaintext highlighter-rouge">resty_foo.lua</code> before compiling it down to a <code class="language-plaintext highlighter-rouge">.o</code> file with the <code class="language-plaintext highlighter-rouge">luajit</code> command-line utility.</p>
<p>It is important to use exactly the same version of LuaJIT when compiling <code class="language-plaintext highlighter-rouge">.lua</code> files to <code class="language-plaintext highlighter-rouge">.o</code> files as building nginx + ngx_lua. This is because the LuaJIT bytecode format may be incompatible between different LuaJIT versions. When the bytecode format is incompatible, you will see a Lua runtime error saying that the Lua module is not found.</p>
<p>When you have multiple <code class="language-plaintext highlighter-rouge">.lua</code> files to compile and link, then just specify their <code class="language-plaintext highlighter-rouge">.o</code> files at the same time in the value of the <code class="language-plaintext highlighter-rouge">--with-ld-opt</code> option. For instance,</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
./configure <span class="nt">--with-ld-opt</span><span class="o">=</span><span class="s2">"/path/to/foo.o /path/to/bar.o"</span> ...
</code></pre></div></div>
<p>If you have just too many <code class="language-plaintext highlighter-rouge">.o</code> files, then it might not be feasible to name them all in a single command. In this case, you can build a static library (or archive) for your <code class="language-plaintext highlighter-rouge">.o</code> files, as in</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
ar rcus libmyluafiles.a <span class="k">*</span>.o
</code></pre></div></div>
<p>then you can link the <code class="language-plaintext highlighter-rouge">myluafiles</code> archive as a whole to your nginx executable:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
./configure <span class="se">\</span>
<span class="nt">--with-ld-opt</span><span class="o">=</span><span class="s2">"-L/path/to/lib -Wl,--whole-archive -lmyluafiles -Wl,--no-whole-archive"</span>
</code></pre></div></div>
<p>where <code class="language-plaintext highlighter-rouge">/path/to/lib</code> is the path of the directory containing the <code class="language-plaintext highlighter-rouge">libmyluafiles.a</code> file. It should be noted that the linker option <code class="language-plaintext highlighter-rouge">--whole-archive</code> is required here because otherwise our archive will be skipped because no symbols in our archive are mentioned in the main parts of the nginx executable.</p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="data-sharing-within-an-nginx-worker">Data Sharing within an Nginx Worker</h1>
<p>To globally share data among all the requests handled by the same nginx worker process, encapsulate the shared data into a Lua module, use the Lua <code class="language-plaintext highlighter-rouge">require</code> builtin to import the module, and then manipulate the shared data in Lua. This works because required Lua modules are loaded only once and all coroutines will share the same copy of the module (both its code and data). Note however that Lua global variables (note, not module-level variables) WILL NOT persist between requests because of the one-coroutine-per-request isolation design.</p>
<p>Here is a complete small example:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="c1">-- mydata.lua</span>
<span class="kd">local</span> <span class="n">_M</span> <span class="o">=</span> <span class="p">{}</span>
<span class="kd">local</span> <span class="n">data</span> <span class="o">=</span> <span class="p">{</span>
<span class="n">dog</span> <span class="o">=</span> <span class="mi">3</span><span class="p">,</span>
<span class="n">cat</span> <span class="o">=</span> <span class="mi">4</span><span class="p">,</span>
<span class="n">pig</span> <span class="o">=</span> <span class="mi">5</span><span class="p">,</span>
<span class="p">}</span>
<span class="k">function</span> <span class="nc">_M</span><span class="p">.</span><span class="nf">get_age</span><span class="p">(</span><span class="n">name</span><span class="p">)</span>
<span class="k">return</span> <span class="n">data</span><span class="p">[</span><span class="n">name</span><span class="p">]</span>
<span class="k">end</span>
<span class="k">return</span> <span class="n">_M</span>
</code></pre></div></div>
<p>and then accessing it from <code class="language-plaintext highlighter-rouge">nginx.conf</code>:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/lua</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">mydata</span> <span class="p">=</span> <span class="s">require</span> <span class="s">"mydata"</span>
<span class="s">ngx.say(mydata.get_age("dog"))</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">mydata</code> module in this example will only be loaded and run on the first request to the location <code class="language-plaintext highlighter-rouge">/lua</code>,
and all subsequent requests to the same nginx worker process will use the reloaded instance of the
module as well as the same copy of the data in it, until a <code class="language-plaintext highlighter-rouge">HUP</code> signal is sent to the Nginx master process to force a reload.
This data sharing technique is essential for high performance Lua applications based on this module.</p>
<p>Note that this data sharing is on a <em>per-worker</em> basis and not on a <em>per-server</em> basis. That is, when there are multiple nginx worker processes under an Nginx master, data sharing cannot cross the process boundary between these workers.</p>
<p>It is usually recommended to share read-only data this way. You can also share changeable data among all the concurrent requests of each nginx worker process as
long as there is <em>no</em> nonblocking I/O operations (including <a href="#ngxsleep">ngx.sleep</a>)
in the middle of your calculations. As long as you do not give the
control back to the nginx event loop and ngx_luas light thread
scheduler (even implicitly), there can never be any race conditions in
between. For this reason, always be very careful when you want to share changeable data on the
worker level. Buggy optimizations can easily lead to hard-to-debug
race conditions under load.</p>
<p>If server-wide data sharing is required, then use one or more of the following approaches:</p>
<ol>
<li>Use the <a href="#ngxshareddict">ngx.shared.DICT</a> API provided by this module.</li>
<li>Use only a single nginx worker and a single server (this is however not recommended when there is a multi core CPU or multiple CPUs in a single machine).</li>
<li>Use data storage mechanisms such as <code class="language-plaintext highlighter-rouge">memcached</code>, <code class="language-plaintext highlighter-rouge">redis</code>, <code class="language-plaintext highlighter-rouge">MySQL</code> or <code class="language-plaintext highlighter-rouge">PostgreSQL</code>. <a href="http://openresty.org">The ngx_openresty bundle</a> associated with this module comes with a set of companion Nginx modules and Lua libraries that provide interfaces with these data storage mechanisms.</li>
</ol>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="known-issues">Known Issues</h1>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h2 id="tcp-socket-connect-operation-issues">TCP socket connect operation issues</h2>
<p>The <a href="#tcpsockconnect">tcpsock:connect</a> method may indicate <code class="language-plaintext highlighter-rouge">success</code> despite connection failures such as with <code class="language-plaintext highlighter-rouge">Connection Refused</code> errors.</p>
<p>However, later attempts to manipulate the cosocket object will fail and return the actual error status message generated by the failed connect operation.</p>
<p>This issue is due to limitations in the Nginx event model and only appears to affect Mac OS X.</p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h2 id="lua-coroutine-yieldingresuming">Lua Coroutine Yielding/Resuming</h2>
<ul>
<li>Because Luas <code class="language-plaintext highlighter-rouge">dofile</code> and <code class="language-plaintext highlighter-rouge">require</code> builtins are currently implemented as C functions in both Lua 5.1 and LuaJIT 2.0/2.1, if the Lua file being loaded by <code class="language-plaintext highlighter-rouge">dofile</code> or <code class="language-plaintext highlighter-rouge">require</code> invokes [ngx.location.capture<em>](#ngxlocationcapture), <a href="#ngxexec">ngx.exec</a>, <a href="#ngxexit">ngx.exit</a>, or other API functions requiring yielding in the *top-level</em> scope of the Lua file, then the Lua error “attempt to yield across C-call boundary” will be raised. To avoid this, put these calls requiring yielding into your own Lua functions in the Lua file instead of the top-level scope of the file.</li>
<li>As the standard Lua 5.1 interpreters VM is not fully resumable, the methods <a href="#ngxlocationcapture">ngx.location.capture</a>, <a href="#ngxlocationcapture_multi">ngx.location.capture_multi</a>, <a href="#ngxredirect">ngx.redirect</a>, <a href="#ngxexec">ngx.exec</a>, and <a href="#ngxexit">ngx.exit</a> cannot be used within the context of a Lua <a href="http://www.lua.org/manual/5.1/manual.html#pdf-pcall">pcall()</a> or <a href="http://www.lua.org/manual/5.1/manual.html#pdf-xpcall">xpcall()</a> or even the first line of the <code class="language-plaintext highlighter-rouge">for ... in ...</code> statement when the standard Lua 5.1 interpreter is used and the <code class="language-plaintext highlighter-rouge">attempt to yield across metamethod/C-call boundary</code> error will be produced. Please use LuaJIT 2.x, which supports a fully resumable VM, to avoid this.</li>
</ul>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h2 id="lua-variable-scope">Lua Variable Scope</h2>
<p>Care must be taken when importing modules and this form should be used:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">xxx</span> <span class="o">=</span> <span class="nb">require</span><span class="p">(</span><span class="s1">'xxx'</span><span class="p">)</span>
</code></pre></div></div>
<p>instead of the old deprecated form:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="nb">require</span><span class="p">(</span><span class="s1">'xxx'</span><span class="p">)</span>
</code></pre></div></div>
<p>Here is the reason: by design, the global environment has exactly the same lifetime as the Nginx request handler associated with it. Each request handler has its own set of Lua global variables and that is the idea of request isolation. The Lua module is actually loaded by the first Nginx request handler and is cached by the <code class="language-plaintext highlighter-rouge">require()</code> built-in in the <code class="language-plaintext highlighter-rouge">package.loaded</code> table for later reference, and the <code class="language-plaintext highlighter-rouge">module()</code> builtin used by some Lua modules has the side effect of setting a global variable to the loaded module table. But this global variable will be cleared at the end of the request handler, and every subsequent request handler all has its own (clean) global environment. So one will get Lua exception for accessing the <code class="language-plaintext highlighter-rouge">nil</code> value.</p>
<p>Generally, use of Lua global variables is a really really bad idea in the context of ngx_lua because</p>
<ol>
<li>misuse of Lua globals has very bad side effects for concurrent requests when these variables are actually supposed to be local only,</li>
<li>Lua global variables require Lua table look-up in the global environment (which is just a Lua table), which is kinda expensive, and</li>
<li>some Lua global variable references are just typos, which are hard to debug.</li>
</ol>
<p>Its <em>highly</em> recommended to always declare them via “local” in the scope that is reasonable.</p>
<p>To find out all the uses of Lua global variables in your Lua code, you can run the <a href="https://github.com/openresty/nginx-devel-utils/blob/master/lua-releng">lua-releng tool</a> across all your .lua source files:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ lua-releng
Checking use of Lua global variables in file lib/foo/bar.lua ...
1 [1489] SETGLOBAL 7 -1 ; contains
55 [1506] GETGLOBAL 7 -3 ; setvar
3 [1545] GETGLOBAL 3 -4 ; varexpand
</code></pre></div></div>
<p>The output says that the line 1489 of file <code class="language-plaintext highlighter-rouge">lib/foo/bar.lua</code> writes to a global variable named <code class="language-plaintext highlighter-rouge">contains</code>, the line 1506 reads from the global variable <code class="language-plaintext highlighter-rouge">setvar</code>, and line 1545 reads the global <code class="language-plaintext highlighter-rouge">varexpand</code>.</p>
<p>This tool will guarantee that local variables in the Lua module functions are all declared with the <code class="language-plaintext highlighter-rouge">local</code> keyword, otherwise a runtime exception will be thrown. It prevents undesirable race conditions while accessing such variables. See <a href="#data-sharing-within-an-nginx-worker">Data Sharing within an Nginx Worker</a> for the reasons behind this.</p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h2 id="locations-configured-by-subrequest-directives-of-other-modules">Locations Configured by Subrequest Directives of Other Modules</h2>
<p>The <a href="#ngxlocationcapture">ngx.location.capture</a> and <a href="#ngxlocationcapture_multi">ngx.location.capture_multi</a> directives cannot capture locations that include the <a href="http://nginx.org/en/docs/http/ngx_http_addition_module.html#add_before_body">add_before_body</a>, <a href="http://nginx.org/en/docs/http/ngx_http_addition_module.html#add_after_body">add_after_body</a>, <a href="http://nginx.org/en/docs/http/ngx_http_auth_request_module.html#auth_request">auth_request</a>, <a href="http://github.com/openresty/echo-nginx-module#echo_location">echo_location</a>, <a href="http://github.com/openresty/echo-nginx-module#echo_location_async">echo_location_async</a>, <a href="http://github.com/openresty/echo-nginx-module#echo_subrequest">echo_subrequest</a>, or <a href="http://github.com/openresty/echo-nginx-module#echo_subrequest_async">echo_subrequest_async</a> directives.</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/foo</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">res</span> <span class="p">=</span> <span class="s">ngx.location.capture("/bar")</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">location</span> <span class="n">/bar</span> <span class="p">{</span>
<span class="kn">echo_location</span> <span class="n">/blah</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">location</span> <span class="n">/blah</span> <span class="p">{</span>
<span class="kn">echo</span> <span class="s">"Success!"</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
$ <span class="k">curl</span> <span class="s">-i</span> <span class="s">http://example.com/foo</span>
</code></pre></div></div>
<p>will not work as expected.</p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h2 id="cosockets-not-available-everywhere">Cosockets Not Available Everywhere</h2>
<p>Due the internal limitations in the nginx core, the cosocket API are disabled in the following contexts: <a href="#log_by_lua">set_by_lua<em>](#set_by_lua), [log_by_lua</em></a>, <a href="#header_filter_by_lua">header_filter_by_lua*</a>, and <a href="#body_filter_by_lua">body_filter_by_lua</a>.</p>
<p>The cosockets are currently also disabled in the <a href="#init_worker_by_lua">init_by_lua<em>](#init_by_lua) and [init_worker_by_lua</em></a> directive contexts but we may add support for these contexts in the future because there is no limitation in the nginx core (or the limitation might be worked around).</p>
<p>There exists a work-around, however, when the original context does <em>not</em> need to wait for the cosocket results. That is, creating a 0-delay timer via the <a href="#ngxtimerat">ngx.timer.at</a> API and do the cosocket results in the timer handler, which runs asynchronously as to the original context creating the timer.</p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h2 id="special-escaping-sequences">Special Escaping Sequences</h2>
<p>PCRE sequences such as <code class="language-plaintext highlighter-rouge">\d</code>, <code class="language-plaintext highlighter-rouge">\s</code>, or <code class="language-plaintext highlighter-rouge">\w</code>, require special attention because in string literals, the backslash character, <code class="language-plaintext highlighter-rouge">\</code>, is stripped out by both the Lua language parser and by the Nginx config file parser before processing. So the following snippet will not work as expected:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="c1"># nginx.conf</span>
<span class="k">?</span> <span class="s">location</span> <span class="n">/test</span> <span class="p">{</span>
<span class="kn">?</span> <span class="s">content_by_lua</span> <span class="s">'</span>
<span class="s">?</span> <span class="s">local</span> <span class="s">regex</span> <span class="p">=</span> <span class="s">"</span><span class="err">\</span><span class="s">d+"</span> <span class="s">--</span> <span class="s">THIS</span> <span class="s">IS</span> <span class="s">WRONG!!</span>
<span class="s">?</span> <span class="s">local</span> <span class="s">m</span> <span class="p">=</span> <span class="s">ngx.re.match("hello,</span> <span class="mi">1234</span><span class="s">",</span> <span class="s">regex)</span>
<span class="s">?</span> <span class="s">if</span> <span class="s">m</span> <span class="s">then</span> <span class="s">ngx.say(m[0])</span> <span class="s">else</span> <span class="s">ngx.say("not</span> <span class="s">matched!")</span> <span class="s">end</span>
<span class="s">?</span> <span class="s">'</span><span class="p">;</span>
<span class="kn">?</span> <span class="err">}</span>
<span class="c1"># evaluates to "not matched!"</span>
</code></pre></div></div>
<p>To avoid this, <em>double</em> escape the backslash:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="c1"># nginx.conf</span>
<span class="k">location</span> <span class="n">/test</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">regex</span> <span class="p">=</span> <span class="s">"</span><span class="err">\\\\</span><span class="s">d+"</span>
<span class="s">local</span> <span class="s">m</span> <span class="p">=</span> <span class="s">ngx.re.match("hello,</span> <span class="mi">1234</span><span class="s">",</span> <span class="s">regex)</span>
<span class="s">if</span> <span class="s">m</span> <span class="s">then</span> <span class="s">ngx.say(m[0])</span> <span class="s">else</span> <span class="s">ngx.say("not</span> <span class="s">matched!")</span> <span class="s">end</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="c1"># evaluates to "1234"</span>
</code></pre></div></div>
<p>Here, <code class="language-plaintext highlighter-rouge">\\\\d+</code> is stripped down to <code class="language-plaintext highlighter-rouge">\\d+</code> by the Nginx config file parser and this is further stripped down to <code class="language-plaintext highlighter-rouge">\d+</code> by the Lua language parser before running.</p>
<p>Alternatively, the regex pattern can be presented as a long-bracketed Lua string literal by encasing it in “long brackets”, <code class="language-plaintext highlighter-rouge">[[...]]</code>, in which case backslashes have to only be escaped once for the Nginx config file parser.</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="c1"># nginx.conf</span>
<span class="k">location</span> <span class="n">/test</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">regex</span> <span class="p">=</span> <span class="s">[[</span><span class="err">\\</span><span class="s">d+]]</span>
<span class="s">local</span> <span class="s">m</span> <span class="p">=</span> <span class="s">ngx.re.match("hello,</span> <span class="mi">1234</span><span class="s">",</span> <span class="s">regex)</span>
<span class="s">if</span> <span class="s">m</span> <span class="s">then</span> <span class="s">ngx.say(m[0])</span> <span class="s">else</span> <span class="s">ngx.say("not</span> <span class="s">matched!")</span> <span class="s">end</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="c1"># evaluates to "1234"</span>
</code></pre></div></div>
<p>Here, <code class="language-plaintext highlighter-rouge">[[\\d+]]</code> is stripped down to <code class="language-plaintext highlighter-rouge">[[\d+]]</code> by the Nginx config file parser and this is processed correctly.</p>
<p>Note that a longer from of the long bracket, <code class="language-plaintext highlighter-rouge">[=[...]=]</code>, may be required if the regex pattern contains <code class="language-plaintext highlighter-rouge">[...]</code> sequences.
The <code class="language-plaintext highlighter-rouge">[=[...]=]</code> form may be used as the default form if desired.</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="c1"># nginx.conf</span>
<span class="k">location</span> <span class="n">/test</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">regex</span> <span class="p">=</span> <span class="s">[=[[0-9]+]=]</span>
<span class="s">local</span> <span class="s">m</span> <span class="p">=</span> <span class="s">ngx.re.match("hello,</span> <span class="mi">1234</span><span class="s">",</span> <span class="s">regex)</span>
<span class="s">if</span> <span class="s">m</span> <span class="s">then</span> <span class="s">ngx.say(m[0])</span> <span class="s">else</span> <span class="s">ngx.say("not</span> <span class="s">matched!")</span> <span class="s">end</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="c1"># evaluates to "1234"</span>
</code></pre></div></div>
<p>An alternative approach to escaping PCRE sequences is to ensure that Lua code is placed in external script files and executed using the various <code class="language-plaintext highlighter-rouge">*_by_lua_file</code> directives.
With this approach, the backslashes are only stripped by the Lua language parser and therefore only need to be escaped once each.</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="c1">-- test.lua</span>
<span class="kd">local</span> <span class="n">regex</span> <span class="o">=</span> <span class="s2">"</span><span class="se">\\</span><span class="s2">d+"</span>
<span class="kd">local</span> <span class="n">m</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">re</span><span class="p">.</span><span class="n">match</span><span class="p">(</span><span class="s2">"hello, 1234"</span><span class="p">,</span> <span class="n">regex</span><span class="p">)</span>
<span class="k">if</span> <span class="n">m</span> <span class="k">then</span> <span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span> <span class="k">else</span> <span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"not matched!"</span><span class="p">)</span> <span class="k">end</span>
<span class="c1">-- evaluates to "1234"</span>
</code></pre></div></div>
<p>Within external script files, PCRE sequences presented as long-bracketed Lua string literals do not require modification.</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="c1">-- test.lua</span>
<span class="kd">local</span> <span class="n">regex</span> <span class="o">=</span> <span class="s">[[\d+]]</span>
<span class="kd">local</span> <span class="n">m</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">re</span><span class="p">.</span><span class="n">match</span><span class="p">(</span><span class="s2">"hello, 1234"</span><span class="p">,</span> <span class="n">regex</span><span class="p">)</span>
<span class="k">if</span> <span class="n">m</span> <span class="k">then</span> <span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span> <span class="k">else</span> <span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"not matched!"</span><span class="p">)</span> <span class="k">end</span>
<span class="c1">-- evaluates to "1234"</span>
</code></pre></div></div>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h2 id="mixing-with-ssi-not-supported">Mixing with SSI Not Supported</h2>
<p>Mixing SSI with ngx_lua in the same Nginx request is not supported at all. Just use ngx_lua exclusively. Everything you can do with SSI can be done atop ngx_lua anyway and it can be more efficient when using ngx_lua.</p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h2 id="spdy-mode-not-fully-supported">SPDY Mode Not Fully Supported</h2>
<p>Certain Lua APIs provided by ngx_lua do not work in Nginxs SPDY mode yet: <a href="#ngxlocationcapture">ngx.location.capture</a>, <a href="#ngxlocationcapture_multi">ngx.location.capture_multi</a>, and <a href="#ngxreqsocket">ngx.req.socket</a>.</p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h2 id="missing-data-on-short-circuited-requests">Missing data on short circuited requests</h2>
<p>Nginx may terminate a request early with (at least):</p>
<ul>
<li>400 (Bad Request)</li>
<li>405 (Not Allowed)</li>
<li>408 (Request Timeout)</li>
<li>414 (Request URI Too Large)</li>
<li>494 (Request Headers Too Large)</li>
<li>499 (Client Closed Request)</li>
<li>500 (Internal Server Error)</li>
<li>501 (Not Implemented)</li>
</ul>
<p>This means that phases that normally run are skipped, such as the rewrite or
access phase. This also means that later phases that are run regardless, e.g.
<a href="#log_by_lua">log_by_lua</a>, will not have access to information that is normally set in those
phases.</p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="todo">TODO</h1>
<ul>
<li>add <code class="language-plaintext highlighter-rouge">*_by_lua_block</code> directives for existing <code class="language-plaintext highlighter-rouge">*_by_lua</code> directives so that we put literal Lua code directly in curly braces instead of an nginx literal string. For example,
```nginx</li>
</ul>
<p>content_by_lua_block {
ngx.say(“hello, world\r\n”)
}</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> which is equivalent to
```nginx
content_by_lua '
ngx.say("hello, world\\r\\n")
';
</code></pre></div></div>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>but the former is much cleaner and nicer. * cosocket: implement LuaSocket's unconnected UDP API. * add support for implementing general TCP servers instead of HTTP servers in Lua. For example, ```lua
</code></pre></div></div>
<p>tcp {
server {
listen 11212;
handler_by_lua
custom Lua code implementing the special TCP server…
;
}
}</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>* add support for implementing general UDP servers instead of HTTP servers in Lua. For example,
```lua
udp {
server {
listen 1953;
handler_by_lua '
-- custom Lua code implementing the special UDP server...
';
}
}
</code></pre></div></div>
<ul>
<li>ssl: implement directives <code class="language-plaintext highlighter-rouge">ssl_certificate_by_lua</code> and <code class="language-plaintext highlighter-rouge">ssl_certificate_by_lua_file</code> to allow using Lua to dynamically serve SSL certificates and keys for downstream SSL handshake. (already done in CloudFlares private branch and powering CloudFlares SSL gateway of its global network. expected to be opensourced in March 2015.)</li>
<li>shm: implement a “shared queue API” to complement the existing <a href="#lua_shared_dict">shared dict</a> API.</li>
<li>cosocket: add support in the context of <a href="#init_by_lua">init_by_lua*</a>.</li>
<li>cosocket: implement the <code class="language-plaintext highlighter-rouge">bind()</code> method for stream-typed cosockets.</li>
<li>cosocket: pool-based backend concurrency level control: implement automatic <code class="language-plaintext highlighter-rouge">connect</code> queueing when the backend concurrency exceeds its connection pool limit.</li>
<li>cosocket: review and merge aviramcs <a href="https://github.com/openresty/lua-nginx-module/pull/290">patch</a> for adding the <code class="language-plaintext highlighter-rouge">bsdrecv</code> method.</li>
<li>add new API function <code class="language-plaintext highlighter-rouge">ngx.resp.add_header</code> to emulate the standard <code class="language-plaintext highlighter-rouge">add_header</code> config directive.</li>
<li><a href="#ngxrematch">ngx.re</a> API: use <code class="language-plaintext highlighter-rouge">false</code> instead of <code class="language-plaintext highlighter-rouge">nil</code> in the resulting match table to indicate non-existent submatch captures, such that we can avoid “holes” in the array table.</li>
<li>review and apply Jader H. Silvas patch for <code class="language-plaintext highlighter-rouge">ngx.re.split()</code>.</li>
<li>review and apply vadim-pavlovs patch for <a href="#ngxlocationcapture">ngx.location.capture</a>s <code class="language-plaintext highlighter-rouge">extra_headers</code> option</li>
<li>use <code class="language-plaintext highlighter-rouge">ngx_hash_t</code> to optimize the built-in header look-up process for <a href="#ngxreqset_header">ngx.req.set_header</a>, <a href="#ngxheaderheader">ngx.header.HEADER</a>, and etc.</li>
<li>add configure options for different strategies of handling the cosocket connection exceeding in the pools.</li>
<li>add directives to run Lua codes when nginx stops.</li>
<li>add <code class="language-plaintext highlighter-rouge">ignore_resp_headers</code>, <code class="language-plaintext highlighter-rouge">ignore_resp_body</code>, and <code class="language-plaintext highlighter-rouge">ignore_resp</code> options to <a href="#ngxlocationcapture">ngx.location.capture</a> and <a href="#ngxlocationcapture_multi">ngx.location.capture_multi</a> methods, to allow micro performance tuning on the user side.</li>
<li>add automatic Lua code time slicing support by yielding and resuming the Lua VM actively via Luas debug hooks.</li>
<li>add <code class="language-plaintext highlighter-rouge">stat</code> mode similar to <a href="https://httpd.apache.org/docs/trunk/mod/mod_lua.html">mod_lua</a>.</li>
</ul>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="changes">Changes</h1>
<p>The changes of every release of this module can be obtained from the ngx_openresty bundles change logs:</p>
<p><a href="http://openresty.org/#Changes">http://openresty.org/#Changes</a></p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="test-suite">Test Suite</h1>
<p>The following dependencies are required to run the test suite:</p>
<ul>
<li>
<p>Nginx version &gt;= 1.4.2</p>
</li>
<li>Perl modules:
<ul>
<li>Test::Nginx: <a href="https://github.com/openresty/test-nginx">https://github.com/openresty/test-nginx</a></li>
</ul>
</li>
<li>Nginx modules:
<ul>
<li><a href="https://github.com/simpl/ngx_devel_kit">ngx_devel_kit</a></li>
<li><a href="https://github.com/openresty/set-misc-nginx-module">ngx_set_misc</a></li>
<li><a href="http://mdounin.ru/files/ngx_http_auth_request_module-0.2.tar.gz">ngx_auth_request</a> (this is not needed if youre using Nginx 1.5.4+.</li>
<li><a href="https://github.com/openresty/echo-nginx-module">ngx_echo</a></li>
<li><a href="https://github.com/openresty/memc-nginx-module">ngx_memc</a></li>
<li><a href="https://github.com/openresty/srcache-nginx-module">ngx_srcache</a></li>
<li>ngx_lua (i.e., this module)</li>
<li><a href="https://github.com/openresty/lua-upstream-nginx-module">ngx_lua_upstream</a></li>
<li><a href="https://github.com/openresty/headers-more-nginx-module">ngx_headers_more</a></li>
<li><a href="https://github.com/openresty/drizzle-nginx-module">ngx_drizzle</a></li>
<li><a href="https://github.com/openresty/rds-json-nginx-module">ngx_rds_json</a></li>
<li><a href="https://github.com/FRiCKLE/ngx_coolkit">ngx_coolkit</a></li>
<li><a href="https://github.com/openresty/redis2-nginx-module">ngx_redis2</a></li>
</ul>
</li>
</ul>
<p>The order in which these modules are added during configuration is important because the position of any filter module in the
filtering chain determines the final output, for example. The correct adding order is shown above.</p>
<ul>
<li>3rd-party Lua libraries:
<ul>
<li><a href="http://www.kyne.com.au/~mark/software/lua-cjson.php">lua-cjson</a></li>
</ul>
</li>
<li>Applications:
<ul>
<li>mysql: create database ngx_test, grant all privileges to user ngx_test, password is ngx_test</li>
<li>memcached: listening on the default port, 11211.</li>
<li>redis: listening on the default port, 6379.</li>
</ul>
</li>
</ul>
<p>See also the <a href="https://github.com/openresty/lua-nginx-module/blob/master/util/build2.sh">developer build script</a> for more details on setting up the testing environment.</p>
<p>To run the whole test suite in the default testing mode:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>cd /path/to/lua-nginx-module
export PATH=/path/to/your/nginx/sbin:$PATH
prove -I/path/to/test-nginx/lib -r t
</code></pre></div></div>
<p>To run specific test files:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>cd /path/to/lua-nginx-module
export PATH=/path/to/your/nginx/sbin:$PATH
prove -I/path/to/test-nginx/lib t/002-content.t t/003-errors.t
</code></pre></div></div>
<p>To run a specific test block in a particular test file, add the line <code class="language-plaintext highlighter-rouge">--- ONLY</code> to the test block you want to run, and then use the <code class="language-plaintext highlighter-rouge">prove</code> utility to run that <code class="language-plaintext highlighter-rouge">.t</code> file.</p>
<p>There are also various testing modes based on mockeagain, valgrind, and etc. Refer to the <a href="http://search.cpan.org/perldoc?Test::Nginx">Test::Nginx documentation</a> for more details for various advanced testing modes. See also the test reports for the Nginx test cluster running on Amazon EC2: <a href="http://qa.openresty.org.">http://qa.openresty.org.</a></p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="copyright-and-license">Copyright and License</h1>
<p>This module is licensed under the BSD license.</p>
<p>Copyright (C) 2009-2015, by Xiaozhe Wang (chaoslawful) <a href="mailto:chaoslawful@gmail.com">chaoslawful@gmail.com</a>.</p>
<p>Copyright (C) 2009-2015, by Yichun “agentzh” Zhang (章亦春) <a href="mailto:agentzh@gmail.com">agentzh@gmail.com</a>, CloudFlare Inc.</p>
<p>All rights reserved.</p>
<p>Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:</p>
<ul>
<li>
<p>Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.</p>
</li>
<li>
<p>Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.</p>
</li>
</ul>
<p>THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="see-also">See Also</h1>
<ul>
<li><a href="https://github.com/openresty/lua-resty-memcached">lua-resty-memcached</a> library based on ngx_lua cosocket.</li>
<li><a href="https://github.com/openresty/lua-resty-redis">lua-resty-redis</a> library based on ngx_lua cosocket.</li>
<li><a href="https://github.com/openresty/lua-resty-mysql">lua-resty-mysql</a> library based on ngx_lua cosocket.</li>
<li><a href="https://github.com/openresty/lua-resty-upload">lua-resty-upload</a> library based on ngx_lua cosocket.</li>
<li><a href="https://github.com/openresty/lua-resty-dns">lua-resty-dns</a> library based on ngx_lua cosocket.</li>
<li><a href="https://github.com/openresty/lua-resty-websocket">lua-resty-websocket</a> library for both WebSocket server and client, based on ngx_lua cosocket.</li>
<li><a href="https://github.com/openresty/lua-resty-string">lua-resty-string</a> library based on <a href="http://luajit.org/ext_ffi.html">LuaJIT FFI</a>.</li>
<li><a href="https://github.com/openresty/lua-resty-lock">lua-resty-lock</a> library for a nonblocking simple lock API.</li>
<li><a href="https://github.com/cloudflare/lua-resty-cookie">lua-resty-cookie</a> library for HTTP cookie manipulation.</li>
<li><a href="http://openresty.org/#RoutingMySQLQueriesBasedOnURIArgs">Routing requests to different MySQL queries based on URI arguments</a></li>
<li><a href="http://openresty.org/#DynamicRoutingBasedOnRedis">Dynamic Routing Based on Redis and Lua</a></li>
<li><a href="http://openresty.org/#UsingLuaRocks">Using LuaRocks with ngx_lua</a></li>
<li><a href="https://github.com/openresty/lua-nginx-module/wiki/Introduction">Introduction to ngx_lua</a></li>
<li><a href="https://github.com/simpl/ngx_devel_kit">ngx_devel_kit</a></li>
<li><a href="http://github.com/openresty/echo-nginx-module">echo-nginx-module</a></li>
<li><a href="http://github.com/openresty/drizzle-nginx-module">drizzle-nginx-module</a></li>
<li><a href="https://github.com/FRiCKLE/ngx_postgres">postgres-nginx-module</a></li>
<li><a href="http://github.com/openresty/memc-nginx-module">memc-nginx-module</a></li>
<li><a href="http://openresty.org">The ngx_openresty bundle</a></li>
<li><a href="https://github.com/openresty/nginx-systemtap-toolkit">Nginx Systemtap Toolkit</a></li>
</ul>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h1 id="directives">Directives</h1>
<ul>
<li><a href="#lua_use_default_type">lua_use_default_type</a></li>
<li><a href="#lua_code_cache">lua_code_cache</a></li>
<li><a href="#lua_regex_cache_max_entries">lua_regex_cache_max_entries</a></li>
<li><a href="#lua_regex_match_limit">lua_regex_match_limit</a></li>
<li><a href="#lua_package_path">lua_package_path</a></li>
<li><a href="#lua_package_cpath">lua_package_cpath</a></li>
<li><a href="#init_by_lua">init_by_lua</a></li>
<li><a href="#init_by_lua_file">init_by_lua_file</a></li>
<li><a href="#init_worker_by_lua">init_worker_by_lua</a></li>
<li><a href="#init_worker_by_lua_file">init_worker_by_lua_file</a></li>
<li><a href="#set_by_lua">set_by_lua</a></li>
<li><a href="#set_by_lua_file">set_by_lua_file</a></li>
<li><a href="#content_by_lua">content_by_lua</a></li>
<li><a href="#content_by_lua_file">content_by_lua_file</a></li>
<li><a href="#rewrite_by_lua">rewrite_by_lua</a></li>
<li><a href="#rewrite_by_lua_file">rewrite_by_lua_file</a></li>
<li><a href="#access_by_lua">access_by_lua</a></li>
<li><a href="#access_by_lua_file">access_by_lua_file</a></li>
<li><a href="#header_filter_by_lua">header_filter_by_lua</a></li>
<li><a href="#header_filter_by_lua_file">header_filter_by_lua_file</a></li>
<li><a href="#body_filter_by_lua">body_filter_by_lua</a></li>
<li><a href="#body_filter_by_lua_file">body_filter_by_lua_file</a></li>
<li><a href="#log_by_lua">log_by_lua</a></li>
<li><a href="#log_by_lua_file">log_by_lua_file</a></li>
<li><a href="#lua_need_request_body">lua_need_request_body</a></li>
<li><a href="#lua_shared_dict">lua_shared_dict</a></li>
<li><a href="#lua_socket_connect_timeout">lua_socket_connect_timeout</a></li>
<li><a href="#lua_socket_send_timeout">lua_socket_send_timeout</a></li>
<li><a href="#lua_socket_send_lowat">lua_socket_send_lowat</a></li>
<li><a href="#lua_socket_read_timeout">lua_socket_read_timeout</a></li>
<li><a href="#lua_socket_buffer_size">lua_socket_buffer_size</a></li>
<li><a href="#lua_socket_pool_size">lua_socket_pool_size</a></li>
<li><a href="#lua_socket_keepalive_timeout">lua_socket_keepalive_timeout</a></li>
<li><a href="#lua_socket_log_errors">lua_socket_log_errors</a></li>
<li><a href="#lua_ssl_ciphers">lua_ssl_ciphers</a></li>
<li><a href="#lua_ssl_crl">lua_ssl_crl</a></li>
<li><a href="#lua_ssl_protocols">lua_ssl_protocols</a></li>
<li><a href="#lua_ssl_trusted_certificate">lua_ssl_trusted_certificate</a></li>
<li><a href="#lua_ssl_verify_depth">lua_ssl_verify_depth</a></li>
<li><a href="#lua_http10_buffering">lua_http10_buffering</a></li>
<li><a href="#rewrite_by_lua_no_postpone">rewrite_by_lua_no_postpone</a></li>
<li><a href="#lua_transform_underscores_in_response_headers">lua_transform_underscores_in_response_headers</a></li>
<li><a href="#lua_check_client_abort">lua_check_client_abort</a></li>
<li><a href="#lua_max_pending_timers">lua_max_pending_timers</a></li>
<li><a href="#lua_max_running_timers">lua_max_running_timers</a></li>
</ul>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h2 id="lua_use_default_type">lua_use_default_type</h2>
<p><strong>syntax:</strong> <em>lua_use_default_type on | off</em></p>
<p><strong>default:</strong> <em>lua_use_default_type on</em></p>
<p><strong>context:</strong> <em>http, server, location, location if</em></p>
<p>Specifies whether to use the MIME type specified by the <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#default_type">default_type</a> directive for the default value of the <code class="language-plaintext highlighter-rouge">Content-Type</code> response header. If you do not want a default <code class="language-plaintext highlighter-rouge">Content-Type</code> response header for your Lua request handlers, then turn this directive off.</p>
<p>This directive is turned on by default.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.9.1</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_code_cache">lua_code_cache</h2>
<p><strong>syntax:</strong> <em>lua_code_cache on | off</em></p>
<p><strong>default:</strong> <em>lua_code_cache on</em></p>
<p><strong>context:</strong> <em>http, server, location, location if</em></p>
<p>Enables or disables the Lua code cache for Lua code in <code class="language-plaintext highlighter-rouge">*_by_lua_file</code> directives (like <a href="#set_by_lua_file">set_by_lua_file</a> and
<a href="#content_by_lua_file">content_by_lua_file</a>) and Lua modules.</p>
<p>When turning off, every request served by ngx_lua will run in a separate Lua VM instance, starting from the <code class="language-plaintext highlighter-rouge">0.9.3</code> release. So the Lua files referenced in <a href="#set_by_lua_file">set_by_lua_file</a>,
<a href="#content_by_lua_file">content_by_lua_file</a>, <a href="#access_by_lua_file">access_by_lua_file</a>,
and etc will not be cached
and all Lua modules used will be loaded from scratch. With this in place, developers can adopt an edit-and-refresh approach.</p>
<p>Please note however, that Lua code written inlined within nginx.conf
such as those specified by <a href="#set_by_lua">set_by_lua</a>, <a href="#content_by_lua">content_by_lua</a>,
<a href="#access_by_lua">access_by_lua</a>, and <a href="#rewrite_by_lua">rewrite_by_lua</a> will not be updated when you edit the inlined Lua code in your <code class="language-plaintext highlighter-rouge">nginx.conf</code> file because only the Nginx config file parser can correctly parse the <code class="language-plaintext highlighter-rouge">nginx.conf</code>
file and the only way is to reload the config file
by sending a <code class="language-plaintext highlighter-rouge">HUP</code> signal or just to restart Nginx.</p>
<p>Even when the code cache is enabled, Lua files which are loaded by <code class="language-plaintext highlighter-rouge">dofile</code> or <code class="language-plaintext highlighter-rouge">loadfile</code>
in *_by_lua_file cannot be cached (unless you cache the results yourself). Usually you can either use the <a href="#init_by_lua">init_by_lua</a>
or <a href="#init-by_lua_file">init_by_lua_file</a> directives to load all such files or just make these Lua files true Lua modules
and load them via <code class="language-plaintext highlighter-rouge">require</code>.</p>
<p>The ngx_lua module does not support the <code class="language-plaintext highlighter-rouge">stat</code> mode available with the
Apache <code class="language-plaintext highlighter-rouge">mod_lua</code> module (yet).</p>
<p>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. For example, the performance a “hello world” Lua example can drop by an order of magnitude after disabling the Lua code cache.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_regex_cache_max_entries">lua_regex_cache_max_entries</h2>
<p><strong>syntax:</strong> <em>lua_regex_cache_max_entries &lt;num&gt;</em></p>
<p><strong>default:</strong> <em>lua_regex_cache_max_entries 1024</em></p>
<p><strong>context:</strong> <em>http</em></p>
<p>Specifies the maximum number of entries allowed in the worker process level compiled regex cache.</p>
<p>The regular expressions used in <a href="#ngxrematch">ngx.re.match</a>, <a href="#ngxregmatch">ngx.re.gmatch</a>, <a href="#ngxresub">ngx.re.sub</a>, and <a href="#ngxregsub">ngx.re.gsub</a> will be cached within this cache if the regex option <code class="language-plaintext highlighter-rouge">o</code> (i.e., compile-once flag) is specified.</p>
<p>The default number of entries allowed is 1024 and when this limit is reached, new regular expressions will not be cached (as if the <code class="language-plaintext highlighter-rouge">o</code> option was not specified) and there will be one, and only one, warning in the <code class="language-plaintext highlighter-rouge">error.log</code> file:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>2011/08/27 23:18:26 [warn] 31997#0: *1 lua exceeding regex cache max entries (1024), ...
</code></pre></div></div>
<p>Do not activate the <code class="language-plaintext highlighter-rouge">o</code> option for regular expressions (and/or <code class="language-plaintext highlighter-rouge">replace</code> string arguments for <a href="#ngxresub">ngx.re.sub</a> and <a href="#ngxregsub">ngx.re.gsub</a>) that are generated <em>on the fly</em> and give rise to infinite variations to avoid hitting the specified limit.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_regex_match_limit">lua_regex_match_limit</h2>
<p><strong>syntax:</strong> <em>lua_regex_match_limit &lt;num&gt;</em></p>
<p><strong>default:</strong> <em>lua_regex_match_limit 0</em></p>
<p><strong>context:</strong> <em>http</em></p>
<p>Specifies the “match limit” used by the PCRE library when executing the <a href="#ngxrematch">ngx.re API</a>. To quote the PCRE manpage, “the limit … has the effect of limiting the amount of backtracking that can take place.”</p>
<p>When the limit is hit, the error string “pcre_exec() failed: -8” will be returned by the <a href="#ngxrematch">ngx.re API</a> functions on the Lua land.</p>
<p>When setting the limit to 0, the default “match limit” when compiling the PCRE library is used. And this is the default value of this directive.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.8.5</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_package_path">lua_package_path</h2>
<p><strong>syntax:</strong> <em>lua_package_path &lt;lua-style-path-str&gt;</em></p>
<p><strong>default:</strong> <em>The content of LUA_PATH environ variable or Luas compiled-in defaults.</em></p>
<p><strong>context:</strong> <em>http</em></p>
<p>Sets the Lua module search path used by scripts specified by <a href="#set_by_lua">set_by_lua</a>,
<a href="#content_by_lua">content_by_lua</a> and others. The path string is in standard Lua path form, and <code class="language-plaintext highlighter-rouge">;;</code>
can be used to stand for the original search paths.</p>
<p>As from the <code class="language-plaintext highlighter-rouge">v0.5.0rc29</code> release, the special notation <code class="language-plaintext highlighter-rouge">$prefix</code> or <code class="language-plaintext highlighter-rouge">${prefix}</code> can be used in the search path string to indicate the path of the <code class="language-plaintext highlighter-rouge">server prefix</code> usually determined by the <code class="language-plaintext highlighter-rouge">-p PATH</code> command-line option while starting the Nginx server.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_package_cpath">lua_package_cpath</h2>
<p><strong>syntax:</strong> <em>lua_package_cpath &lt;lua-style-cpath-str&gt;</em></p>
<p><strong>default:</strong> <em>The content of LUA_CPATH environment variable or Luas compiled-in defaults.</em></p>
<p><strong>context:</strong> <em>http</em></p>
<p>Sets the Lua C-module search path used by scripts specified by <a href="#set_by_lua">set_by_lua</a>,
<a href="#content_by_lua">content_by_lua</a> and others. The cpath string is in standard Lua cpath form, and <code class="language-plaintext highlighter-rouge">;;</code>
can be used to stand for the original cpath.</p>
<p>As from the <code class="language-plaintext highlighter-rouge">v0.5.0rc29</code> release, the special notation <code class="language-plaintext highlighter-rouge">$prefix</code> or <code class="language-plaintext highlighter-rouge">${prefix}</code> can be used in the search path string to indicate the path of the <code class="language-plaintext highlighter-rouge">server prefix</code> usually determined by the <code class="language-plaintext highlighter-rouge">-p PATH</code> command-line option while starting the Nginx server.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="init_by_lua">init_by_lua</h2>
<p><strong>syntax:</strong> <em>init_by_lua &lt;lua-script-str&gt;</em></p>
<p><strong>context:</strong> <em>http</em></p>
<p><strong>phase:</strong> <em>loading-config</em></p>
<p>Runs the Lua code specified by the argument <code class="language-plaintext highlighter-rouge">&lt;lua-script-str&gt;</code> on the global Lua VM level when the Nginx master process (if any) is loading the Nginx config file.</p>
<p>When Nginx receives the <code class="language-plaintext highlighter-rouge">HUP</code> signal and starts reloading the config file, the Lua VM will also be re-created and <code class="language-plaintext highlighter-rouge">init_by_lua</code> will run again on the new Lua VM. In case that the <a href="#lua_code_cache">lua_code_cache</a> directive is turned off (default on), the <code class="language-plaintext highlighter-rouge">init_by_lua</code> handler will run upon every request because in this special mode a standalone Lua VM is always created for each request.</p>
<p>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:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">init_by_lua</span> <span class="s">'cjson</span> <span class="p">=</span> <span class="s">require</span> <span class="s">"cjson"'</span><span class="p">;</span>
<span class="k">server</span> <span class="p">{</span>
<span class="kn">location</span> <span class="p">=</span> <span class="n">/api</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">ngx.say(cjson.encode(</span><span class="p">{</span><span class="kn">dog</span> <span class="p">=</span> <span class="mi">5</span><span class="s">,</span> <span class="s">cat</span> <span class="p">=</span> <span class="mi">6</span><span class="err">}</span><span class="s">))</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>You can also initialize the <a href="#lua_shared_dict">lua_shared_dict</a> shm storage at this phase. Here is an example for this:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">lua_shared_dict</span> <span class="s">dogs</span> <span class="mi">1m</span><span class="p">;</span>
<span class="k">init_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">dogs</span> <span class="p">=</span> <span class="s">ngx.shared.dogs</span><span class="p">;</span>
<span class="k">dogs:set</span><span class="s">("Tom",</span> <span class="mi">56</span><span class="s">)</span>
<span class="s">'</span><span class="p">;</span>
<span class="k">server</span> <span class="p">{</span>
<span class="kn">location</span> <span class="p">=</span> <span class="n">/api</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">dogs</span> <span class="p">=</span> <span class="s">ngx.shared.dogs</span><span class="p">;</span>
<span class="kn">ngx.say</span><span class="s">(dogs:get("Tom"))</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>But note that, the <a href="#lua_shared_dict">lua_shared_dict</a>s shm storage will not be cleared through a config reload (via the <code class="language-plaintext highlighter-rouge">HUP</code> signal, for example). So if you do <em>not</em> want to re-initialize the shm storage in your <code class="language-plaintext highlighter-rouge">init_by_lua</code> code in this case, then you just need to set a custom flag in the shm storage and always check the flag in your <code class="language-plaintext highlighter-rouge">init_by_lua</code> code.</p>
<p>Because the Lua code in this context runs before Nginx forks its worker processes (if any), data or code loaded here will enjoy the <a href="http://en.wikipedia.org/wiki/Copy-on-write">Copy-on-write (COW)</a> feature provided by many operating systems among all the worker processes, thus saving a lot of memory.</p>
<p>Do <em>not</em> initialize your own Lua global variables in this context because use of Lua global variables have performance penalties and can lead to global namespace pollution (see the <a href="#lua-variable-scope">Lua Variable Scope</a> section for more details). The recommended way is to use proper <a href="http://www.lua.org/manual/5.1/manual.html#5.3">Lua module</a> files (but do not use the standard Lua function <a href="http://www.lua.org/manual/5.1/manual.html#pdf-module">module()</a> to define Lua modules because it pollutes the global namespace as well) and call <a href="http://www.lua.org/manual/5.1/manual.html#pdf-require">require()</a> to load your own module files in <code class="language-plaintext highlighter-rouge">init_by_lua</code> or other contexts (<a href="http://www.lua.org/manual/5.1/manual.html#pdf-require">require()</a> does cache the loaded Lua modules in the global <code class="language-plaintext highlighter-rouge">package.loaded</code> table in the Lua registry so your modules will only loaded once for the whole Lua VM instance).</p>
<p>Only a small set of the <a href="#nginx-api-for-lua">Nginx API for Lua</a> is supported in this context:</p>
<ul>
<li>Logging APIs: <a href="#ngxlog">ngx.log</a> and <a href="#print">print</a>,</li>
<li>Shared Dictionary API: <a href="#ngxshareddict">ngx.shared.DICT</a>.</li>
</ul>
<p>More Nginx APIs for Lua may be supported in this context upon future user requests.</p>
<p>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 upstreams host names) at the configure-loading phase.</p>
<p>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 <code class="language-plaintext highlighter-rouge">root</code> account.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.5</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="init_by_lua_file">init_by_lua_file</h2>
<p><strong>syntax:</strong> <em>init_by_lua_file &lt;path-to-lua-script-file&gt;</em></p>
<p><strong>context:</strong> <em>http</em></p>
<p><strong>phase:</strong> <em>loading-config</em></p>
<p>Equivalent to <a href="#init_by_lua">init_by_lua</a>, except that the file specified by <code class="language-plaintext highlighter-rouge">&lt;path-to-lua-script-file&gt;</code> contains the Lua code or <a href="#lualuajit-bytecode-support">Lua/LuaJIT bytecode</a> to be executed.</p>
<p>When a relative path like <code class="language-plaintext highlighter-rouge">foo/bar.lua</code> is given, they will be turned into the absolute path relative to the <code class="language-plaintext highlighter-rouge">server prefix</code> path determined by the <code class="language-plaintext highlighter-rouge">-p PATH</code> command-line option while starting the Nginx server.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.5</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="init_worker_by_lua">init_worker_by_lua</h2>
<p><strong>syntax:</strong> <em>init_worker_by_lua &lt;lua-script-str&gt;</em></p>
<p><strong>context:</strong> <em>http</em></p>
<p><strong>phase:</strong> <em>starting-worker</em></p>
<p>Runs the specified Lua code upon every Nginx worker processs startup when the master process is enabled. When the master process is disabled, this hook will just run after <a href="#init_by_lua">init_by_lua*</a>.</p>
<p>This hook is often used to create per-worker reoccurring timers (via the <a href="#ngxtimerat">ngx.timer.at</a> Lua API), either for backend healthcheck or other timed routine work. Below is an example,</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">init_worker_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">delay</span> <span class="p">=</span> <span class="mi">3</span> <span class="s">--</span> <span class="s">in</span> <span class="s">seconds</span>
<span class="s">local</span> <span class="s">new_timer</span> <span class="p">=</span> <span class="s">ngx.timer.at</span>
<span class="s">local</span> <span class="s">log</span> <span class="p">=</span> <span class="s">ngx.log</span>
<span class="s">local</span> <span class="s">ERR</span> <span class="p">=</span> <span class="s">ngx.ERR</span>
<span class="s">local</span> <span class="s">check</span>
<span class="s">check</span> <span class="p">=</span> <span class="s">function(premature)</span>
<span class="s">if</span> <span class="s">not</span> <span class="s">premature</span> <span class="s">then</span>
<span class="s">--</span> <span class="s">do</span> <span class="s">the</span> <span class="s">health</span> <span class="s">check</span> <span class="s">or</span> <span class="s">other</span> <span class="s">routine</span> <span class="s">work</span>
<span class="s">local</span> <span class="s">ok,</span> <span class="s">err</span> <span class="p">=</span> <span class="s">new_timer(delay,</span> <span class="s">check)</span>
<span class="s">if</span> <span class="s">not</span> <span class="s">ok</span> <span class="s">then</span>
<span class="s">log(ERR,</span> <span class="s">"failed</span> <span class="s">to</span> <span class="s">create</span> <span class="s">timer:</span> <span class="s">",</span> <span class="s">err)</span>
<span class="s">return</span>
<span class="s">end</span>
<span class="s">end</span>
<span class="s">end</span>
<span class="s">local</span> <span class="s">ok,</span> <span class="s">err</span> <span class="p">=</span> <span class="s">new_timer(delay,</span> <span class="s">check)</span>
<span class="s">if</span> <span class="s">not</span> <span class="s">ok</span> <span class="s">then</span>
<span class="s">log(ERR,</span> <span class="s">"failed</span> <span class="s">to</span> <span class="s">create</span> <span class="s">timer:</span> <span class="s">",</span> <span class="s">err)</span>
<span class="s">return</span>
<span class="s">end</span>
<span class="s">'</span><span class="p">;</span>
</code></pre></div></div>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.9.5</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="init_worker_by_lua_file">init_worker_by_lua_file</h2>
<p><strong>syntax:</strong> <em>init_worker_by_lua_file &lt;lua-file-path&gt;</em></p>
<p><strong>context:</strong> <em>http</em></p>
<p><strong>phase:</strong> <em>starting-worker</em></p>
<p>Similar to <a href="#init_worker_by_lua">init_worker_by_lua</a>, but accepts the file path to a Lua source file or Lua bytecode file.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.9.5</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="set_by_lua">set_by_lua</h2>
<p><strong>syntax:</strong> <em>set_by_lua $res &lt;lua-script-str&gt; [$arg1 $arg2 …]</em></p>
<p><strong>context:</strong> <em>server, server if, location, location if</em></p>
<p><strong>phase:</strong> <em>rewrite</em></p>
<p>Executes code specified in <code class="language-plaintext highlighter-rouge">&lt;lua-script-str&gt;</code> with optional input arguments <code class="language-plaintext highlighter-rouge">$arg1 $arg2 ...</code>, and returns string output to <code class="language-plaintext highlighter-rouge">$res</code>.
The code in <code class="language-plaintext highlighter-rouge">&lt;lua-script-str&gt;</code> can make <a href="#nginx-api-for-lua">API calls</a> and can retrieve input arguments from the <code class="language-plaintext highlighter-rouge">ngx.arg</code> table (index starts from <code class="language-plaintext highlighter-rouge">1</code> and increases sequentially).</p>
<p>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.</p>
<p>This directive is implemented by injecting custom commands into the standard <a href="http://nginx.org/en/docs/http/ngx_http_rewrite_module.html">ngx_http_rewrite_module</a>s command list. Because <a href="http://nginx.org/en/docs/http/ngx_http_rewrite_module.html">ngx_http_rewrite_module</a> does not support nonblocking I/O in its commands, Lua APIs requiring yielding the current Lua “light thread” cannot work in this directive.</p>
<p>At least the following API functions are currently disabled within the context of <code class="language-plaintext highlighter-rouge">set_by_lua</code>:</p>
<ul>
<li>Output API functions (e.g., <a href="#ngxsay">ngx.say</a> and <a href="#ngxsend_headers">ngx.send_headers</a>)</li>
<li>Control API functions (e.g., <a href="#ngxexit">ngx.exit</a>)</li>
<li>Subrequest API functions (e.g., <a href="#ngxlocationcapture">ngx.location.capture</a> and <a href="#ngxlocationcapture_multi">ngx.location.capture_multi</a>)</li>
<li>Cosocket API functions (e.g., <a href="#ngxsockettcp">ngx.socket.tcp</a> and <a href="#ngxreqsocket">ngx.req.socket</a>).</li>
<li>Sleeping API function <a href="#ngxsleep">ngx.sleep</a>.</li>
</ul>
<p>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 <a href="#ngxvarvariable">ngx.var.VARIABLE</a> interface.</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/foo</span> <span class="p">{</span>
<span class="kn">set</span> <span class="nv">$diff</span> <span class="s">''</span><span class="p">;</span> <span class="c1"># we have to predefine the $diff variable here</span>
<span class="kn">set_by_lua</span> <span class="nv">$sum</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">a</span> <span class="p">=</span> <span class="mi">32</span>
<span class="s">local</span> <span class="s">b</span> <span class="p">=</span> <span class="mi">56</span>
<span class="s">ngx.var.diff</span> <span class="p">=</span> <span class="s">a</span> <span class="s">-</span> <span class="s">b</span><span class="p">;</span> <span class="kn">--</span> <span class="s">write</span> <span class="s">to</span> <span class="nv">$diff</span> <span class="s">directly</span>
<span class="s">return</span> <span class="s">a</span> <span class="s">+</span> <span class="s">b</span><span class="p">;</span> <span class="kn">--</span> <span class="s">return</span> <span class="s">the</span> <span class="nv">$sum</span> <span class="s">value</span> <span class="s">normally</span>
<span class="s">'</span><span class="p">;</span>
<span class="kn">echo</span> <span class="s">"sum</span> <span class="p">=</span> <span class="nv">$sum</span><span class="s">,</span> <span class="s">diff</span> <span class="p">=</span> <span class="nv">$diff</span><span class="s">"</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>This directive can be freely mixed with all directives of the <a href="http://nginx.org/en/docs/http/ngx_http_rewrite_module.html">ngx_http_rewrite_module</a>, <a href="http://github.com/openresty/set-misc-nginx-module">set-misc-nginx-module</a>, and <a href="http://github.com/openresty/array-var-nginx-module">array-var-nginx-module</a> modules. All of these directives will run in the same order as they appear in the config file.</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">set</span> <span class="nv">$foo</span> <span class="mi">32</span><span class="p">;</span>
<span class="k">set_by_lua</span> <span class="nv">$bar</span> <span class="s">'tonumber(ngx.var.foo)</span> <span class="s">+</span> <span class="mi">1</span><span class="s">'</span><span class="p">;</span>
<span class="k">set</span> <span class="nv">$baz</span> <span class="s">"bar:</span> <span class="nv">$bar</span><span class="s">"</span><span class="p">;</span> <span class="c1"># $baz == "bar: 33"</span>
</code></pre></div></div>
<p>As from the <code class="language-plaintext highlighter-rouge">v0.5.0rc29</code> release, Nginx variable interpolation is disabled in the <code class="language-plaintext highlighter-rouge">&lt;lua-script-str&gt;</code> argument of this directive and therefore, the dollar sign character (<code class="language-plaintext highlighter-rouge">$</code>) can be used directly.</p>
<p>This directive requires the <a href="https://github.com/simpl/ngx_devel_kit">ngx_devel_kit</a> module.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="set_by_lua_file">set_by_lua_file</h2>
<p><strong>syntax:</strong> <em>set_by_lua_file $res &lt;path-to-lua-script-file&gt; [$arg1 $arg2 …]</em></p>
<p><strong>context:</strong> <em>server, server if, location, location if</em></p>
<p><strong>phase:</strong> <em>rewrite</em></p>
<p>Equivalent to <a href="#set_by_lua">set_by_lua</a>, except that the file specified by <code class="language-plaintext highlighter-rouge">&lt;path-to-lua-script-file&gt;</code> contains the Lua code, or, as from the <code class="language-plaintext highlighter-rouge">v0.5.0rc32</code> release, the <a href="#lualuajit-bytecode-support">Lua/LuaJIT bytecode</a> to be executed.</p>
<p>Nginx variable interpolation is supported in the <code class="language-plaintext highlighter-rouge">&lt;path-to-lua-script-file&gt;</code> argument string of this directive. But special care must be taken for injection attacks.</p>
<p>When a relative path like <code class="language-plaintext highlighter-rouge">foo/bar.lua</code> is given, they will be turned into the absolute path relative to the <code class="language-plaintext highlighter-rouge">server prefix</code> path determined by the <code class="language-plaintext highlighter-rouge">-p PATH</code> command-line option while starting the Nginx server.</p>
<p>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 <a href="#lua_code_cache">lua_code_cache</a> <code class="language-plaintext highlighter-rouge">off</code> in <code class="language-plaintext highlighter-rouge">nginx.conf</code> to avoid reloading Nginx.</p>
<p>This directive requires the <a href="https://github.com/simpl/ngx_devel_kit">ngx_devel_kit</a> module.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="content_by_lua">content_by_lua</h2>
<p><strong>syntax:</strong> <em>content_by_lua &lt;lua-script-str&gt;</em></p>
<p><strong>context:</strong> <em>location, location if</em></p>
<p><strong>phase:</strong> <em>content</em></p>
<p>Acts as a “content handler” and executes Lua code string specified in <code class="language-plaintext highlighter-rouge">&lt;lua-script-str&gt;</code> for every request.
The Lua code may make <a href="#nginx-api-for-lua">API calls</a> and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox).</p>
<p>Do not use this directive and other content handler directives in the same location. For example, this directive and the <a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass">proxy_pass</a> directive should not be used in the same location.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="content_by_lua_file">content_by_lua_file</h2>
<p><strong>syntax:</strong> <em>content_by_lua_file &lt;path-to-lua-script-file&gt;</em></p>
<p><strong>context:</strong> <em>location, location if</em></p>
<p><strong>phase:</strong> <em>content</em></p>
<p>Equivalent to <a href="#content_by_lua">content_by_lua</a>, except that the file specified by <code class="language-plaintext highlighter-rouge">&lt;path-to-lua-script-file&gt;</code> contains the Lua code, or, as from the <code class="language-plaintext highlighter-rouge">v0.5.0rc32</code> release, the <a href="#lualuajit-bytecode-support">Lua/LuaJIT bytecode</a> to be executed.</p>
<p>Nginx variables can be used in the <code class="language-plaintext highlighter-rouge">&lt;path-to-lua-script-file&gt;</code> string to provide flexibility. This however carries some risks and is not ordinarily recommended.</p>
<p>When a relative path like <code class="language-plaintext highlighter-rouge">foo/bar.lua</code> is given, they will be turned into the absolute path relative to the <code class="language-plaintext highlighter-rouge">server prefix</code> path determined by the <code class="language-plaintext highlighter-rouge">-p PATH</code> command-line option while starting the Nginx server.</p>
<p>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 <a href="#lua_code_cache">lua_code_cache</a> <code class="language-plaintext highlighter-rouge">off</code> in <code class="language-plaintext highlighter-rouge">nginx.conf</code> to avoid reloading Nginx.</p>
<p>Nginx variables are supported in the file path for dynamic dispatch, for example:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="c1"># WARNING: contents in nginx var must be carefully filtered,</span>
<span class="c1"># otherwise there'll be great security risk!</span>
<span class="k">location</span> <span class="p">~</span> <span class="sr">^/app/([-_a-zA-Z0-9/]+)</span> <span class="p">{</span>
<span class="kn">set</span> <span class="nv">$path</span> <span class="nv">$1</span><span class="p">;</span>
<span class="kn">content_by_lua_file</span> <span class="n">/path/to/lua/app/root/</span><span class="nv">$path</span><span class="s">.lua</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>But be very careful about malicious user inputs and always carefully validate or filter out the user-supplied path components.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="rewrite_by_lua">rewrite_by_lua</h2>
<p><strong>syntax:</strong> <em>rewrite_by_lua &lt;lua-script-str&gt;</em></p>
<p><strong>context:</strong> <em>http, server, location, location if</em></p>
<p><strong>phase:</strong> <em>rewrite tail</em></p>
<p>Acts as a rewrite phase handler and executes Lua code string specified in <code class="language-plaintext highlighter-rouge">&lt;lua-script-str&gt;</code> for every request.
The Lua code may make <a href="#nginx-api-for-lua">API calls</a> and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox).</p>
<p>Note that this handler always runs <em>after</em> the standard <a href="http://nginx.org/en/docs/http/ngx_http_rewrite_module.html">ngx_http_rewrite_module</a>. So the following will work as expected:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/foo</span> <span class="p">{</span>
<span class="kn">set</span> <span class="nv">$a</span> <span class="mi">12</span><span class="p">;</span> <span class="c1"># create and initialize $a</span>
<span class="kn">set</span> <span class="nv">$b</span> <span class="s">""</span><span class="p">;</span> <span class="c1"># create and initialize $b</span>
<span class="kn">rewrite_by_lua</span> <span class="s">'ngx.var.b</span> <span class="p">=</span> <span class="s">tonumber(ngx.var.a)</span> <span class="s">+</span> <span class="mi">1</span><span class="s">'</span><span class="p">;</span>
<span class="kn">echo</span> <span class="s">"res</span> <span class="p">=</span> <span class="nv">$b</span><span class="s">"</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>because <code class="language-plaintext highlighter-rouge">set $a 12</code> and <code class="language-plaintext highlighter-rouge">set $b ""</code> run <em>before</em> <a href="#rewrite_by_lua">rewrite_by_lua</a>.</p>
<p>On the other hand, the following will not work as expected:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">?</span> <span class="s">location</span> <span class="n">/foo</span> <span class="p">{</span>
<span class="kn">?</span> <span class="s">set</span> <span class="nv">$a</span> <span class="mi">12</span><span class="p">;</span> <span class="c1"># create and initialize $a</span>
<span class="kn">?</span> <span class="s">set</span> <span class="nv">$b</span> <span class="s">''</span><span class="p">;</span> <span class="c1"># create and initialize $b</span>
<span class="kn">?</span> <span class="s">rewrite_by_lua</span> <span class="s">'ngx.var.b</span> <span class="p">=</span> <span class="s">tonumber(ngx.var.a)</span> <span class="s">+</span> <span class="mi">1</span><span class="s">'</span><span class="p">;</span>
<span class="kn">?</span> <span class="s">if</span> <span class="s">(</span><span class="nv">$b</span> <span class="p">=</span> <span class="s">'13')</span> <span class="p">{</span>
<span class="kn">?</span> <span class="s">rewrite</span> <span class="s">^</span> <span class="n">/bar</span> <span class="s">redirect</span><span class="p">;</span>
<span class="kn">?</span> <span class="s">break</span><span class="p">;</span>
<span class="kn">?</span> <span class="err">}</span>
<span class="s">?</span>
<span class="s">?</span> <span class="s">echo</span> <span class="s">"res</span> <span class="p">=</span> <span class="nv">$b</span><span class="s">"</span><span class="p">;</span>
<span class="kn">?</span> <span class="err">}</span>
</code></pre></div></div>
<p>because <code class="language-plaintext highlighter-rouge">if</code> runs <em>before</em> <a href="#rewrite_by_lua">rewrite_by_lua</a> even if it is placed after <a href="#rewrite_by_lua">rewrite_by_lua</a> in the config.</p>
<p>The right way of doing this is as follows:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/foo</span> <span class="p">{</span>
<span class="kn">set</span> <span class="nv">$a</span> <span class="mi">12</span><span class="p">;</span> <span class="c1"># create and initialize $a</span>
<span class="kn">set</span> <span class="nv">$b</span> <span class="s">''</span><span class="p">;</span> <span class="c1"># create and initialize $b</span>
<span class="kn">rewrite_by_lua</span> <span class="s">'</span>
<span class="s">ngx.var.b</span> <span class="p">=</span> <span class="s">tonumber(ngx.var.a)</span> <span class="s">+</span> <span class="mi">1</span>
<span class="s">if</span> <span class="s">tonumber(ngx.var.b)</span> <span class="p">==</span> <span class="mi">13</span> <span class="s">then</span>
<span class="s">return</span> <span class="s">ngx.redirect("/bar")</span><span class="p">;</span>
<span class="kn">end</span>
<span class="s">'</span><span class="p">;</span>
<span class="kn">echo</span> <span class="s">"res</span> <span class="p">=</span> <span class="nv">$b</span><span class="s">"</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Note that the <a href="http://www.grid.net.ru/nginx/eval.en.html">ngx_eval</a> module can be approximated by using <a href="#rewrite_by_lua">rewrite_by_lua</a>. For example,</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/</span> <span class="p">{</span>
<span class="kn">eval</span> <span class="nv">$res</span> <span class="p">{</span>
<span class="kn">proxy_pass</span> <span class="s">http://foo.com/check-spam</span><span class="p">;</span>
<span class="p">}</span>
<span class="kn">if</span> <span class="s">(</span><span class="nv">$res</span> <span class="p">=</span> <span class="s">'spam')</span> <span class="p">{</span>
<span class="kn">rewrite</span> <span class="s">^</span> <span class="n">/terms-of-use.html</span> <span class="s">redirect</span><span class="p">;</span>
<span class="p">}</span>
<span class="kn">fastcgi_pass</span> <span class="s">...</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>can be implemented in ngx_lua as:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="p">=</span> <span class="n">/check-spam</span> <span class="p">{</span>
<span class="kn">internal</span><span class="p">;</span>
<span class="kn">proxy_pass</span> <span class="s">http://foo.com/check-spam</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">location</span> <span class="n">/</span> <span class="p">{</span>
<span class="kn">rewrite_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">res</span> <span class="p">=</span> <span class="s">ngx.location.capture("/check-spam")</span>
<span class="s">if</span> <span class="s">res.body</span> <span class="p">==</span> <span class="s">"spam"</span> <span class="s">then</span>
<span class="s">return</span> <span class="s">ngx.redirect("/terms-of-use.html")</span>
<span class="s">end</span>
<span class="s">'</span><span class="p">;</span>
<span class="kn">fastcgi_pass</span> <span class="s">...</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Just as any other rewrite phase handlers, <a href="#rewrite_by_lua">rewrite_by_lua</a> also runs in subrequests.</p>
<p>Note that when calling <code class="language-plaintext highlighter-rouge">ngx.exit(ngx.OK)</code> within a <a href="#rewrite_by_lua">rewrite_by_lua</a> handler, the nginx request processing control flow will still continue to the content handler. To terminate the current request from within a <a href="#rewrite_by_lua">rewrite_by_lua</a> handler, calling <a href="#ngxexit">ngx.exit</a> with status &gt;= 200 (<code class="language-plaintext highlighter-rouge">ngx.HTTP_OK</code>) and status &lt; 300 (<code class="language-plaintext highlighter-rouge">ngx.HTTP_SPECIAL_RESPONSE</code>) for successful quits and <code class="language-plaintext highlighter-rouge">ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)</code> (or its friends) for failures.</p>
<p>If the <a href="http://nginx.org/en/docs/http/ngx_http_rewrite_module.html">ngx_http_rewrite_module</a>s <a href="http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite">rewrite</a> directive is used to change the URI and initiate location re-lookups (internal redirections), then any <a href="#rewrite_by_lua">rewrite_by_lua</a> or <a href="#rewrite_by_lua_file">rewrite_by_lua_file</a> code sequences within the current location will not be executed. For example,</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/foo</span> <span class="p">{</span>
<span class="kn">rewrite</span> <span class="s">^</span> <span class="n">/bar</span><span class="p">;</span>
<span class="kn">rewrite_by_lua</span> <span class="s">'ngx.exit(503)'</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">location</span> <span class="n">/bar</span> <span class="p">{</span>
<span class="kn">...</span>
<span class="err">}</span>
</code></pre></div></div>
<p>Here the Lua code <code class="language-plaintext highlighter-rouge">ngx.exit(503)</code> will never run. This will be the case if <code class="language-plaintext highlighter-rouge">rewrite ^ /bar last</code> is used as this will similarly initiate an internal redirection. If the <code class="language-plaintext highlighter-rouge">break</code> modifier is used instead, there will be no internal redirection and the <code class="language-plaintext highlighter-rouge">rewrite_by_lua</code> code will be executed.</p>
<p>The <code class="language-plaintext highlighter-rouge">rewrite_by_lua</code> code will always run at the end of the <code class="language-plaintext highlighter-rouge">rewrite</code> request-processing phase unless <a href="#rewrite_by_lua_no_postpone">rewrite_by_lua_no_postpone</a> is turned on.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="rewrite_by_lua_file">rewrite_by_lua_file</h2>
<p><strong>syntax:</strong> <em>rewrite_by_lua_file &lt;path-to-lua-script-file&gt;</em></p>
<p><strong>context:</strong> <em>http, server, location, location if</em></p>
<p><strong>phase:</strong> <em>rewrite tail</em></p>
<p>Equivalent to <a href="#rewrite_by_lua">rewrite_by_lua</a>, except that the file specified by <code class="language-plaintext highlighter-rouge">&lt;path-to-lua-script-file&gt;</code> contains the Lua code, or, as from the <code class="language-plaintext highlighter-rouge">v0.5.0rc32</code> release, the <a href="#lualuajit-bytecode-support">Lua/LuaJIT bytecode</a> to be executed.</p>
<p>Nginx variables can be used in the <code class="language-plaintext highlighter-rouge">&lt;path-to-lua-script-file&gt;</code> string to provide flexibility. This however carries some risks and is not ordinarily recommended.</p>
<p>When a relative path like <code class="language-plaintext highlighter-rouge">foo/bar.lua</code> is given, they will be turned into the absolute path relative to the <code class="language-plaintext highlighter-rouge">server prefix</code> path determined by the <code class="language-plaintext highlighter-rouge">-p PATH</code> command-line option while starting the Nginx server.</p>
<p>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 <a href="#lua_code_cache">lua_code_cache</a> <code class="language-plaintext highlighter-rouge">off</code> in <code class="language-plaintext highlighter-rouge">nginx.conf</code> to avoid reloading Nginx.</p>
<p>The <code class="language-plaintext highlighter-rouge">rewrite_by_lua_file</code> code will always run at the end of the <code class="language-plaintext highlighter-rouge">rewrite</code> request-processing phase unless <a href="#rewrite_by_lua_no_postpone">rewrite_by_lua_no_postpone</a> is turned on.</p>
<p>Nginx variables are supported in the file path for dynamic dispatch just as in <a href="#content_by_lua_file">content_by_lua_file</a>.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="access_by_lua">access_by_lua</h2>
<p><strong>syntax:</strong> <em>access_by_lua &lt;lua-script-str&gt;</em></p>
<p><strong>context:</strong> <em>http, server, location, location if</em></p>
<p><strong>phase:</strong> <em>access tail</em></p>
<p>Acts as an access phase handler and executes Lua code string specified in <code class="language-plaintext highlighter-rouge">&lt;lua-script-str&gt;</code> for every request.
The Lua code may make <a href="#nginx-api-for-lua">API calls</a> and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox).</p>
<p>Note that this handler always runs <em>after</em> the standard <a href="http://nginx.org/en/docs/http/ngx_http_access_module.html">ngx_http_access_module</a>. So the following will work as expected:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/</span> <span class="p">{</span>
<span class="kn">deny</span> <span class="mf">192.168</span><span class="s">.1.1</span><span class="p">;</span>
<span class="kn">allow</span> <span class="mf">192.168</span><span class="s">.1.0/24</span><span class="p">;</span>
<span class="kn">allow</span> <span class="mf">10.1</span><span class="s">.1.0/16</span><span class="p">;</span>
<span class="kn">deny</span> <span class="s">all</span><span class="p">;</span>
<span class="kn">access_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">res</span> <span class="p">=</span> <span class="s">ngx.location.capture("/mysql",</span> <span class="p">{</span> <span class="kn">...</span> <span class="err">}</span><span class="s">)</span>
<span class="s">...</span>
<span class="s">'</span><span class="p">;</span>
<span class="c1"># proxy_pass/fastcgi_pass/...</span>
<span class="p">}</span>
</code></pre></div></div>
<p>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 <a href="#access_by_lua">access_by_lua</a>.</p>
<p>Note that the <a href="http://mdounin.ru/hg/ngx_http_auth_request_module/">ngx_auth_request</a> module can be approximated by using <a href="#access_by_lua">access_by_lua</a>:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/</span> <span class="p">{</span>
<span class="kn">auth_request</span> <span class="n">/auth</span><span class="p">;</span>
<span class="c1"># proxy_pass/fastcgi_pass/postgres_pass/...</span>
<span class="p">}</span>
</code></pre></div></div>
<p>can be implemented in ngx_lua as:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/</span> <span class="p">{</span>
<span class="kn">access_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">res</span> <span class="p">=</span> <span class="s">ngx.location.capture("/auth")</span>
<span class="s">if</span> <span class="s">res.status</span> <span class="p">==</span> <span class="s">ngx.HTTP_OK</span> <span class="s">then</span>
<span class="s">return</span>
<span class="s">end</span>
<span class="s">if</span> <span class="s">res.status</span> <span class="p">==</span> <span class="s">ngx.HTTP_FORBIDDEN</span> <span class="s">then</span>
<span class="s">ngx.exit(res.status)</span>
<span class="s">end</span>
<span class="s">ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)</span>
<span class="s">'</span><span class="p">;</span>
<span class="c1"># proxy_pass/fastcgi_pass/postgres_pass/...</span>
<span class="p">}</span>
</code></pre></div></div>
<p>As with other access phase handlers, <a href="#access_by_lua">access_by_lua</a> will <em>not</em> run in subrequests.</p>
<p>Note that when calling <code class="language-plaintext highlighter-rouge">ngx.exit(ngx.OK)</code> within a <a href="#access_by_lua">access_by_lua</a> handler, the nginx request processing control flow will still continue to the content handler. To terminate the current request from within a <a href="#access_by_lua">access_by_lua</a> handler, calling <a href="#ngxexit">ngx.exit</a> with status &gt;= 200 (<code class="language-plaintext highlighter-rouge">ngx.HTTP_OK</code>) and status &lt; 300 (<code class="language-plaintext highlighter-rouge">ngx.HTTP_SPECIAL_RESPONSE</code>) for successful quits and <code class="language-plaintext highlighter-rouge">ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)</code> (or its friends) for failures.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="access_by_lua_file">access_by_lua_file</h2>
<p><strong>syntax:</strong> <em>access_by_lua_file &lt;path-to-lua-script-file&gt;</em></p>
<p><strong>context:</strong> <em>http, server, location, location if</em></p>
<p><strong>phase:</strong> <em>access tail</em></p>
<p>Equivalent to <a href="#access_by_lua">access_by_lua</a>, except that the file specified by <code class="language-plaintext highlighter-rouge">&lt;path-to-lua-script-file&gt;</code> contains the Lua code, or, as from the <code class="language-plaintext highlighter-rouge">v0.5.0rc32</code> release, the <a href="#lualuajit-bytecode-support">Lua/LuaJIT bytecode</a> to be executed.</p>
<p>Nginx variables can be used in the <code class="language-plaintext highlighter-rouge">&lt;path-to-lua-script-file&gt;</code> string to provide flexibility. This however carries some risks and is not ordinarily recommended.</p>
<p>When a relative path like <code class="language-plaintext highlighter-rouge">foo/bar.lua</code> is given, they will be turned into the absolute path relative to the <code class="language-plaintext highlighter-rouge">server prefix</code> path determined by the <code class="language-plaintext highlighter-rouge">-p PATH</code> command-line option while starting the Nginx server.</p>
<p>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 <a href="#lua_code_cache">lua_code_cache</a> <code class="language-plaintext highlighter-rouge">off</code> in <code class="language-plaintext highlighter-rouge">nginx.conf</code> to avoid repeatedly reloading Nginx.</p>
<p>Nginx variables are supported in the file path for dynamic dispatch just as in <a href="#content_by_lua_file">content_by_lua_file</a>.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="header_filter_by_lua">header_filter_by_lua</h2>
<p><strong>syntax:</strong> <em>header_filter_by_lua &lt;lua-script-str&gt;</em></p>
<p><strong>context:</strong> <em>http, server, location, location if</em></p>
<p><strong>phase:</strong> <em>output-header-filter</em></p>
<p>Uses Lua code specified in <code class="language-plaintext highlighter-rouge">&lt;lua-script-str&gt;</code> to define an output header filter.</p>
<p>Note that the following API functions are currently disabled within this context:</p>
<ul>
<li>Output API functions (e.g., <a href="#ngxsay">ngx.say</a> and <a href="#ngxsend_headers">ngx.send_headers</a>)</li>
<li>Control API functions (e.g., <a href="#ngxredirect">ngx.redirect</a> and <a href="#ngxexec">ngx.exec</a>)</li>
<li>Subrequest API functions (e.g., <a href="#ngxlocationcapture">ngx.location.capture</a> and <a href="#ngxlocationcapture_multi">ngx.location.capture_multi</a>)</li>
<li>Cosocket API functions (e.g., <a href="#ngxsockettcp">ngx.socket.tcp</a> and <a href="#ngxreqsocket">ngx.req.socket</a>).</li>
</ul>
<p>Here is an example of overriding a response header (or adding one if absent) in our Lua header filter:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/</span> <span class="p">{</span>
<span class="kn">proxy_pass</span> <span class="s">http://mybackend</span><span class="p">;</span>
<span class="kn">header_filter_by_lua</span> <span class="s">'ngx.header.Foo</span> <span class="p">=</span> <span class="s">"blah"'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.2.1rc20</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="header_filter_by_lua_file">header_filter_by_lua_file</h2>
<p><strong>syntax:</strong> <em>header_filter_by_lua_file &lt;path-to-lua-script-file&gt;</em></p>
<p><strong>context:</strong> <em>http, server, location, location if</em></p>
<p><strong>phase:</strong> <em>output-header-filter</em></p>
<p>Equivalent to <a href="#header_filter_by_lua">header_filter_by_lua</a>, except that the file specified by <code class="language-plaintext highlighter-rouge">&lt;path-to-lua-script-file&gt;</code> contains the Lua code, or as from the <code class="language-plaintext highlighter-rouge">v0.5.0rc32</code> release, the <a href="#lualuajit-bytecode-support">Lua/LuaJIT bytecode</a> to be executed.</p>
<p>When a relative path like <code class="language-plaintext highlighter-rouge">foo/bar.lua</code> is given, they will be turned into the absolute path relative to the <code class="language-plaintext highlighter-rouge">server prefix</code> path determined by the <code class="language-plaintext highlighter-rouge">-p PATH</code> command-line option while starting the Nginx server.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.2.1rc20</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="body_filter_by_lua">body_filter_by_lua</h2>
<p><strong>syntax:</strong> <em>body_filter_by_lua &lt;lua-script-str&gt;</em></p>
<p><strong>context:</strong> <em>http, server, location, location if</em></p>
<p><strong>phase:</strong> <em>output-body-filter</em></p>
<p>Uses Lua code specified in <code class="language-plaintext highlighter-rouge">&lt;lua-script-str&gt;</code> to define an output body filter.</p>
<p>The input data chunk is passed via <a href="#ngxarg">ngx.arg</a>[1] (as a Lua string value) and the “eof” flag indicating the end of the response body data stream is passed via <a href="#ngxarg">ngx.arg</a>[2] (as a Lua boolean value).</p>
<p>Behind the scene, the “eof” flag is just the <code class="language-plaintext highlighter-rouge">last_buf</code> (for main requests) or <code class="language-plaintext highlighter-rouge">last_in_chain</code> (for subrequests) flag of the Nginx chain link buffers. (Before the <code class="language-plaintext highlighter-rouge">v0.7.14</code> release, the “eof” flag does not work at all in subrequests.)</p>
<p>The output data stream can be aborted immediately by running the following Lua statement:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">return</span> <span class="n">ngx</span><span class="p">.</span><span class="n">ERROR</span>
</code></pre></div></div>
<p>This will truncate the response body and usually result in incomplete and also invalid responses.</p>
<p>The Lua code can pass its own modified version of the input data chunk to the downstream Nginx output body filters by overriding <a href="#ngxarg">ngx.arg</a>[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:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/</span> <span class="p">{</span>
<span class="kn">proxy_pass</span> <span class="s">http://mybackend</span><span class="p">;</span>
<span class="kn">body_filter_by_lua</span> <span class="s">'ngx.arg[1]</span> <span class="p">=</span> <span class="s">string.upper(ngx.arg[1])'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>When setting <code class="language-plaintext highlighter-rouge">nil</code> or an empty Lua string value to <code class="language-plaintext highlighter-rouge">ngx.arg[1]</code>, no data chunk will be passed to the downstream Nginx output filters at all.</p>
<p>Likewise, new “eof” flag can also be specified by setting a boolean value to <a href="#ngxarg">ngx.arg</a>[2]. For example,</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/t</span> <span class="p">{</span>
<span class="kn">echo</span> <span class="s">hello</span> <span class="s">world</span><span class="p">;</span>
<span class="kn">echo</span> <span class="s">hiya</span> <span class="s">globe</span><span class="p">;</span>
<span class="kn">body_filter_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">chunk</span> <span class="p">=</span> <span class="s">ngx.arg[1]</span>
<span class="s">if</span> <span class="s">string.match(chunk,</span> <span class="s">"hello")</span> <span class="s">then</span>
<span class="s">ngx.arg[2]</span> <span class="p">=</span> <span class="s">true</span> <span class="s">--</span> <span class="s">new</span> <span class="s">eof</span>
<span class="s">return</span>
<span class="s">end</span>
<span class="s">--</span> <span class="s">just</span> <span class="s">throw</span> <span class="s">away</span> <span class="s">any</span> <span class="s">remaining</span> <span class="s">chunk</span> <span class="s">data</span>
<span class="s">ngx.arg[1]</span> <span class="p">=</span> <span class="s">nil</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Then <code class="language-plaintext highlighter-rouge">GET /t</code> will just return the output</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>hello world
</code></pre></div></div>
<p>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.</p>
<p>When the Lua code may change the length of the response body, then it is required to always clear out the <code class="language-plaintext highlighter-rouge">Content-Length</code> response header (if any) in a header filter to enforce streaming output, as in</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/foo</span> <span class="p">{</span>
<span class="c1"># fastcgi_pass/proxy_pass/...</span>
<span class="kn">header_filter_by_lua</span> <span class="s">'ngx.header.content_length</span> <span class="p">=</span> <span class="s">nil'</span><span class="p">;</span>
<span class="kn">body_filter_by_lua</span> <span class="s">'ngx.arg[1]</span> <span class="p">=</span> <span class="s">string.len(ngx.arg[1])</span> <span class="s">..</span> <span class="s">"</span><span class="err">\\</span><span class="s">n"'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Note that the following API functions are currently disabled within this context due to the limitations in NGINX output filters current implementation:</p>
<ul>
<li>Output API functions (e.g., <a href="#ngxsay">ngx.say</a> and <a href="#ngxsend_headers">ngx.send_headers</a>)</li>
<li>Control API functions (e.g., <a href="#ngxexit">ngx.exit</a> and <a href="#ngxexec">ngx.exec</a>)</li>
<li>Subrequest API functions (e.g., <a href="#ngxlocationcapture">ngx.location.capture</a> and <a href="#ngxlocationcapture_multi">ngx.location.capture_multi</a>)</li>
<li>Cosocket API functions (e.g., <a href="#ngxsockettcp">ngx.socket.tcp</a> and <a href="#ngxreqsocket">ngx.req.socket</a>).</li>
</ul>
<p>Nginx output filters may be called multiple times for a single request because response body may be delivered in chunks. Thus, the Lua code specified by in this directive may also run multiple times in the lifetime of a single HTTP request.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc32</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="body_filter_by_lua_file">body_filter_by_lua_file</h2>
<p><strong>syntax:</strong> <em>body_filter_by_lua_file &lt;path-to-lua-script-file&gt;</em></p>
<p><strong>context:</strong> <em>http, server, location, location if</em></p>
<p><strong>phase:</strong> <em>output-body-filter</em></p>
<p>Equivalent to <a href="#body_filter_by_lua">body_filter_by_lua</a>, except that the file specified by <code class="language-plaintext highlighter-rouge">&lt;path-to-lua-script-file&gt;</code> contains the Lua code, or, as from the <code class="language-plaintext highlighter-rouge">v0.5.0rc32</code> release, the <a href="#lualuajit-bytecode-support">Lua/LuaJIT bytecode</a> to be executed.</p>
<p>When a relative path like <code class="language-plaintext highlighter-rouge">foo/bar.lua</code> is given, they will be turned into the absolute path relative to the <code class="language-plaintext highlighter-rouge">server prefix</code> path determined by the <code class="language-plaintext highlighter-rouge">-p PATH</code> command-line option while starting the Nginx server.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc32</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="log_by_lua">log_by_lua</h2>
<p><strong>syntax:</strong> <em>log_by_lua &lt;lua-script-str&gt;</em></p>
<p><strong>context:</strong> <em>http, server, location, location if</em></p>
<p><strong>phase:</strong> <em>log</em></p>
<p>Run the Lua source code inlined as the <code class="language-plaintext highlighter-rouge">&lt;lua-script-str&gt;</code> at the <code class="language-plaintext highlighter-rouge">log</code> request processing phase. This does not replace the current access logs, but runs after.</p>
<p>Note that the following API functions are currently disabled within this context:</p>
<ul>
<li>Output API functions (e.g., <a href="#ngxsay">ngx.say</a> and <a href="#ngxsend_headers">ngx.send_headers</a>)</li>
<li>Control API functions (e.g., <a href="#ngxexit">ngx.exit</a>)</li>
<li>Subrequest API functions (e.g., <a href="#ngxlocationcapture">ngx.location.capture</a> and <a href="#ngxlocationcapture_multi">ngx.location.capture_multi</a>)</li>
<li>Cosocket API functions (e.g., <a href="#ngxsockettcp">ngx.socket.tcp</a> and <a href="#ngxreqsocket">ngx.req.socket</a>).</li>
</ul>
<p>Here is an example of gathering average data for <a href="http://nginx.org/en/docs/http/ngx_http_upstream_module.html#var_upstream_response_time">$upstream_response_time</a>:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">lua_shared_dict</span> <span class="s">log_dict</span> <span class="mi">5M</span><span class="p">;</span>
<span class="k">server</span> <span class="p">{</span>
<span class="kn">location</span> <span class="n">/</span> <span class="p">{</span>
<span class="kn">proxy_pass</span> <span class="s">http://mybackend</span><span class="p">;</span>
<span class="kn">log_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">log_dict</span> <span class="p">=</span> <span class="s">ngx.shared.log_dict</span>
<span class="s">local</span> <span class="s">upstream_time</span> <span class="p">=</span> <span class="s">tonumber(ngx.var.upstream_response_time)</span>
<span class="s">local</span> <span class="s">sum</span> <span class="p">=</span> <span class="s">log_dict:get("upstream_time-sum")</span> <span class="s">or</span> <span class="mi">0</span>
<span class="s">sum</span> <span class="p">=</span> <span class="s">sum</span> <span class="s">+</span> <span class="s">upstream_time</span>
<span class="s">log_dict:set("upstream_time-sum",</span> <span class="s">sum)</span>
<span class="s">local</span> <span class="s">newval,</span> <span class="s">err</span> <span class="p">=</span> <span class="s">log_dict:incr("upstream_time-nb",</span> <span class="mi">1</span><span class="s">)</span>
<span class="s">if</span> <span class="s">not</span> <span class="s">newval</span> <span class="s">and</span> <span class="s">err</span> <span class="p">==</span> <span class="s">"not</span> <span class="s">found"</span> <span class="s">then</span>
<span class="s">log_dict:add("upstream_time-nb",</span> <span class="mi">0</span><span class="s">)</span>
<span class="s">log_dict:incr("upstream_time-nb",</span> <span class="mi">1</span><span class="s">)</span>
<span class="s">end</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="kn">location</span> <span class="p">=</span> <span class="n">/status</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">log_dict</span> <span class="p">=</span> <span class="s">ngx.shared.log_dict</span>
<span class="s">local</span> <span class="s">sum</span> <span class="p">=</span> <span class="s">log_dict:get("upstream_time-sum")</span>
<span class="s">local</span> <span class="s">nb</span> <span class="p">=</span> <span class="s">log_dict:get("upstream_time-nb")</span>
<span class="s">if</span> <span class="s">nb</span> <span class="s">and</span> <span class="s">sum</span> <span class="s">then</span>
<span class="s">ngx.say("average</span> <span class="s">upstream</span> <span class="s">response</span> <span class="s">time:</span> <span class="s">",</span> <span class="s">sum</span> <span class="n">/</span> <span class="s">nb,</span>
<span class="s">"</span> <span class="s">(",</span> <span class="s">nb,</span> <span class="s">"</span> <span class="s">reqs)")</span>
<span class="s">else</span>
<span class="s">ngx.say("no</span> <span class="s">data</span> <span class="s">yet")</span>
<span class="s">end</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc31</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="log_by_lua_file">log_by_lua_file</h2>
<p><strong>syntax:</strong> <em>log_by_lua_file &lt;path-to-lua-script-file&gt;</em></p>
<p><strong>context:</strong> <em>http, server, location, location if</em></p>
<p><strong>phase:</strong> <em>log</em></p>
<p>Equivalent to <a href="#log_by_lua">log_by_lua</a>, except that the file specified by <code class="language-plaintext highlighter-rouge">&lt;path-to-lua-script-file&gt;</code> contains the Lua code, or, as from the <code class="language-plaintext highlighter-rouge">v0.5.0rc32</code> release, the <a href="#lualuajit-bytecode-support">Lua/LuaJIT bytecode</a> to be executed.</p>
<p>When a relative path like <code class="language-plaintext highlighter-rouge">foo/bar.lua</code> is given, they will be turned into the absolute path relative to the <code class="language-plaintext highlighter-rouge">server prefix</code> path determined by the <code class="language-plaintext highlighter-rouge">-p PATH</code> command-line option while starting the Nginx server.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc31</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_need_request_body">lua_need_request_body</h2>
<table>
<tbody>
<tr>
<td><strong>syntax:</strong> *lua_need_request_body &lt;on</td>
<td>off&gt;*</td>
</tr>
</tbody>
</table>
<p><strong>default:</strong> <em>off</em></p>
<p><strong>context:</strong> <em>http, server, location, location if</em></p>
<p><strong>phase:</strong> <em>depends on usage</em></p>
<p>Determines whether to force the request body data to be read before running rewrite/access/access_by_lua* or not. The Nginx core does not read the client request body by default and if request body data is required, then this directive should be turned <code class="language-plaintext highlighter-rouge">on</code> or the <a href="#ngxreqread_body">ngx.req.read_body</a> function should be called within the Lua code.</p>
<p>To read the request body data within the <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_body">$request_body</a> variable,
<a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size">client_body_buffer_size</a> must have the same value as <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size">client_max_body_size</a>. Because when the content length exceeds <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size">client_body_buffer_size</a> but less than <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size">client_max_body_size</a>, Nginx will buffer the data into a temporary file on the disk, which will lead to empty value in the <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#var_request_body">$request_body</a> variable.</p>
<p>If the current location includes <a href="#rewrite_by_lua">rewrite_by_lua</a> or <a href="#rewrite_by_lua_file">rewrite_by_lua_file</a> directives,
then the request body will be read just before the <a href="#rewrite_by_lua">rewrite_by_lua</a> or <a href="#rewrite_by_lua_file">rewrite_by_lua_file</a> code is run (and also at the
<code class="language-plaintext highlighter-rouge">rewrite</code> phase). Similarly, if only <a href="#content_by_lua">content_by_lua</a> is specified,
the request body will not be read until the content handlers Lua code is
about to run (i.e., the request body will be read during the content phase).</p>
<p>It is recommended however, to use the <a href="#ngxreqread_body">ngx.req.read_body</a> and <a href="#ngxreqdiscard_body">ngx.req.discard_body</a> functions for finer control over the request body reading process instead.</p>
<p>This also applies to <a href="#access_by_lua">access_by_lua</a> and <a href="#access_by_lua_file">access_by_lua_file</a>.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_shared_dict">lua_shared_dict</h2>
<p><strong>syntax:</strong> <em>lua_shared_dict &lt;name&gt; &lt;size&gt;</em></p>
<p><strong>default:</strong> <em>no</em></p>
<p><strong>context:</strong> <em>http</em></p>
<p><strong>phase:</strong> <em>depends on usage</em></p>
<p>Declares a shared memory zone, <code class="language-plaintext highlighter-rouge">&lt;name&gt;</code>, to serve as storage for the shm based Lua dictionary <code class="language-plaintext highlighter-rouge">ngx.shared.&lt;name&gt;</code>.</p>
<p>Shared memory zones are always shared by all the nginx worker processes in the current nginx server instance.</p>
<p>The <code class="language-plaintext highlighter-rouge">&lt;size&gt;</code> argument accepts size units such as <code class="language-plaintext highlighter-rouge">k</code> and <code class="language-plaintext highlighter-rouge">m</code>:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">http</span> <span class="p">{</span>
<span class="kn">lua_shared_dict</span> <span class="s">dogs</span> <span class="mi">10m</span><span class="p">;</span>
<span class="kn">...</span>
<span class="err">}</span>
</code></pre></div></div>
<p>See <a href="#ngxshareddict">ngx.shared.DICT</a> for details.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc22</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_socket_connect_timeout">lua_socket_connect_timeout</h2>
<p><strong>syntax:</strong> <em>lua_socket_connect_timeout &lt;time&gt;</em></p>
<p><strong>default:</strong> <em>lua_socket_connect_timeout 60s</em></p>
<p><strong>context:</strong> <em>http, server, location</em></p>
<p>This directive controls the default timeout value used in TCP/unix-domain socket objects <a href="#tcpsockconnect">connect</a> method and can be overridden by the <a href="#tcpsocksettimeout">settimeout</a> method.</p>
<p>The <code class="language-plaintext highlighter-rouge">&lt;time&gt;</code> argument can be an integer, with an optional time unit, like <code class="language-plaintext highlighter-rouge">s</code> (second), <code class="language-plaintext highlighter-rouge">ms</code> (millisecond), <code class="language-plaintext highlighter-rouge">m</code> (minute). The default time unit is <code class="language-plaintext highlighter-rouge">s</code>, i.e., “second”. The default setting is <code class="language-plaintext highlighter-rouge">60s</code>.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc1</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_socket_send_timeout">lua_socket_send_timeout</h2>
<p><strong>syntax:</strong> <em>lua_socket_send_timeout &lt;time&gt;</em></p>
<p><strong>default:</strong> <em>lua_socket_send_timeout 60s</em></p>
<p><strong>context:</strong> <em>http, server, location</em></p>
<p>Controls the default timeout value used in TCP/unix-domain socket objects <a href="#tcpsocksend">send</a> method and can be overridden by the <a href="#tcpsocksettimeout">settimeout</a> method.</p>
<p>The <code class="language-plaintext highlighter-rouge">&lt;time&gt;</code> argument can be an integer, with an optional time unit, like <code class="language-plaintext highlighter-rouge">s</code> (second), <code class="language-plaintext highlighter-rouge">ms</code> (millisecond), <code class="language-plaintext highlighter-rouge">m</code> (minute). The default time unit is <code class="language-plaintext highlighter-rouge">s</code>, i.e., “second”. The default setting is <code class="language-plaintext highlighter-rouge">60s</code>.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc1</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_socket_send_lowat">lua_socket_send_lowat</h2>
<p><strong>syntax:</strong> <em>lua_socket_send_lowat &lt;size&gt;</em></p>
<p><strong>default:</strong> <em>lua_socket_send_lowat 0</em></p>
<p><strong>context:</strong> <em>http, server, location</em></p>
<p>Controls the <code class="language-plaintext highlighter-rouge">lowat</code> (low water) value for the cosocket send buffer.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_socket_read_timeout">lua_socket_read_timeout</h2>
<p><strong>syntax:</strong> <em>lua_socket_read_timeout &lt;time&gt;</em></p>
<p><strong>default:</strong> <em>lua_socket_read_timeout 60s</em></p>
<p><strong>context:</strong> <em>http, server, location</em></p>
<p><strong>phase:</strong> <em>depends on usage</em></p>
<p>This directive controls the default timeout value used in TCP/unix-domain socket objects <a href="#tcpsockreceive">receive</a> method and iterator functions returned by the <a href="#tcpsockreceiveuntil">receiveuntil</a> method. This setting can be overridden by the <a href="#tcpsocksettimeout">settimeout</a> method.</p>
<p>The <code class="language-plaintext highlighter-rouge">&lt;time&gt;</code> argument can be an integer, with an optional time unit, like <code class="language-plaintext highlighter-rouge">s</code> (second), <code class="language-plaintext highlighter-rouge">ms</code> (millisecond), <code class="language-plaintext highlighter-rouge">m</code> (minute). The default time unit is <code class="language-plaintext highlighter-rouge">s</code>, i.e., “second”. The default setting is <code class="language-plaintext highlighter-rouge">60s</code>.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc1</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_socket_buffer_size">lua_socket_buffer_size</h2>
<p><strong>syntax:</strong> <em>lua_socket_buffer_size &lt;size&gt;</em></p>
<p><strong>default:</strong> <em>lua_socket_buffer_size 4k/8k</em></p>
<p><strong>context:</strong> <em>http, server, location</em></p>
<p>Specifies the buffer size used by cosocket reading operations.</p>
<p>This buffer does not have to be that big to hold everything at the same time because cosocket supports 100% non-buffered reading and parsing. So even <code class="language-plaintext highlighter-rouge">1</code> byte buffer size should still work everywhere but the performance could be terrible.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc1</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_socket_pool_size">lua_socket_pool_size</h2>
<p><strong>syntax:</strong> <em>lua_socket_pool_size &lt;size&gt;</em></p>
<p><strong>default:</strong> <em>lua_socket_pool_size 30</em></p>
<p><strong>context:</strong> <em>http, server, location</em></p>
<p>Specifies the size limit (in terms of connection count) for every cosocket connection pool associated with every remote server (i.e., identified by either the host-port pair or the unix domain socket file path).</p>
<p>Default to 30 connections for every pool.</p>
<p>When the connection pool exceeds the available size limit, the least recently used (idle) connection already in the pool will be closed to make room for the current connection.</p>
<p>Note that the cosocket connection pool is per nginx worker process rather than per nginx server instance, so size limit specified here also applies to every single nginx worker process.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc1</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_socket_keepalive_timeout">lua_socket_keepalive_timeout</h2>
<p><strong>syntax:</strong> <em>lua_socket_keepalive_timeout &lt;time&gt;</em></p>
<p><strong>default:</strong> <em>lua_socket_keepalive_timeout 60s</em></p>
<p><strong>context:</strong> <em>http, server, location</em></p>
<p>This directive controls the default maximal idle time of the connections in the cosocket built-in connection pool. When this timeout reaches, idle connections will be closed and removed from the pool. This setting can be overridden by cosocket objects <a href="#tcpsocksetkeepalive">setkeepalive</a> method.</p>
<p>The <code class="language-plaintext highlighter-rouge">&lt;time&gt;</code> argument can be an integer, with an optional time unit, like <code class="language-plaintext highlighter-rouge">s</code> (second), <code class="language-plaintext highlighter-rouge">ms</code> (millisecond), <code class="language-plaintext highlighter-rouge">m</code> (minute). The default time unit is <code class="language-plaintext highlighter-rouge">s</code>, i.e., “second”. The default setting is <code class="language-plaintext highlighter-rouge">60s</code>.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc1</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_socket_log_errors">lua_socket_log_errors</h2>
<table>
<tbody>
<tr>
<td><strong>syntax:</strong> *lua_socket_log_errors on</td>
<td>off*</td>
</tr>
</tbody>
</table>
<p><strong>default:</strong> <em>lua_socket_log_errors on</em></p>
<p><strong>context:</strong> <em>http, server, location</em></p>
<p>This directive can be used to toggle error logging when a failure occurs for the TCP or UDP cosockets. If you are already doing proper error handling and logging in your Lua code, then it is recommended to turn this directive off to prevent data flushing in your nginx error log files (which is usually rather expensive).</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.13</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_ssl_ciphers">lua_ssl_ciphers</h2>
<p><strong>syntax:</strong> <em>lua_ssl_ciphers &lt;ciphers&gt;</em></p>
<p><strong>default:</strong> <em>lua_ssl_ciphers DEFAULT</em></p>
<p><strong>context:</strong> <em>http, server, location</em></p>
<p>Specifies the enabled ciphers for requests to a SSL/TLS server in the <a href="#tcpsocksslhandshake">tcpsock:sslhandshake</a> method. The ciphers are specified in the format understood by the OpenSSL library.</p>
<p>The full list can be viewed using the “openssl ciphers” command.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.9.11</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_ssl_crl">lua_ssl_crl</h2>
<p><strong>syntax:</strong> <em>lua_ssl_crl &lt;file&gt;</em></p>
<p><strong>default:</strong> <em>no</em></p>
<p><strong>context:</strong> <em>http, server, location</em></p>
<p>Specifies a file with revoked certificates (CRL) in the PEM format used to verify the certificate of the SSL/TLS server in the <a href="#tcpsocksslhandshake">tcpsock:sslhandshake</a> method.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.9.11</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_ssl_protocols">lua_ssl_protocols</h2>
<p><strong>syntax:</strong> <em>lua_ssl_protocols [SSLv2] [SSLv3] [TLSv1] [TLSv1.1] [TLSv1.2]</em></p>
<p><strong>default:</strong> <em>lua_ssl_protocols SSLv3 TLSv1 TLSv1.1 TLSv1.2</em></p>
<p><strong>context:</strong> <em>http, server, location</em></p>
<p>Enables the specified protocols for requests to a SSL/TLS server in the <a href="#tcpsocksslhandshake">tcpsock:sslhandshake</a> method.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.9.11</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_ssl_trusted_certificate">lua_ssl_trusted_certificate</h2>
<p><strong>syntax:</strong> <em>lua_ssl_trusted_certificate &lt;file&gt;</em></p>
<p><strong>default:</strong> <em>no</em></p>
<p><strong>context:</strong> <em>http, server, location</em></p>
<p>Specifies a file path with trusted CA certificates in the PEM format used to verify the certificate of the SSL/TLS server in the <a href="#tcpsocksslhandshake">tcpsock:sslhandshake</a> method.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.9.11</code> release.</p>
<p>See also <a href="#lua_ssl_verify_depth">lua_ssl_verify_depth</a>.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_ssl_verify_depth">lua_ssl_verify_depth</h2>
<p><strong>syntax:</strong> <em>lua_ssl_verify_depth &lt;number&gt;</em></p>
<p><strong>default:</strong> <em>lua_ssl_verify_depth 1</em></p>
<p><strong>context:</strong> <em>http, server, location</em></p>
<p>Sets the verification depth in the server certificates chain.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.9.11</code> release.</p>
<p>See also <a href="#lua_ssl_trusted_certificate">lua_ssl_trusted_certificate</a>.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_http10_buffering">lua_http10_buffering</h2>
<table>
<tbody>
<tr>
<td><strong>syntax:</strong> *lua_http10_buffering on</td>
<td>off*</td>
</tr>
</tbody>
</table>
<p><strong>default:</strong> <em>lua_http10_buffering on</em></p>
<p><strong>context:</strong> <em>http, server, location, location-if</em></p>
<p>Enables or disables automatic response buffering for HTTP 1.0 (or older) requests. This buffering mechanism is mainly used for HTTP 1.0 keep-alive which replies on a proper <code class="language-plaintext highlighter-rouge">Content-Length</code> response header.</p>
<p>If the Lua code explicitly sets a <code class="language-plaintext highlighter-rouge">Content-Length</code> response header before sending the headers (either explicitly via <a href="#ngxsend_headers">ngx.send_headers</a> or implicitly via the first <a href="#ngxsay">ngx.say</a> or <a href="#ngxprint">ngx.print</a> call), then the HTTP 1.0 response buffering will be disabled even when this directive is turned on.</p>
<p>To output very large response data in a streaming fashion (via the <a href="#ngxflush">ngx.flush</a> call, for example), this directive MUST be turned off to minimize memory usage.</p>
<p>This directive is turned <code class="language-plaintext highlighter-rouge">on</code> by default.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc19</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="rewrite_by_lua_no_postpone">rewrite_by_lua_no_postpone</h2>
<table>
<tbody>
<tr>
<td><strong>syntax:</strong> *rewrite_by_lua_no_postpone on</td>
<td>off*</td>
</tr>
</tbody>
</table>
<p><strong>default:</strong> <em>rewrite_by_lua_no_postpone off</em></p>
<p><strong>context:</strong> <em>http</em></p>
<p>Controls whether or not to disable postponing <a href="#rewrite_by_lua">rewrite_by_lua</a> and <a href="#rewrite_by_lua_file">rewrite_by_lua_file</a> directives to run at the end of the <code class="language-plaintext highlighter-rouge">rewrite</code> request-processing phase. By default, this directive is turned off and the Lua code is postponed to run at the end of the <code class="language-plaintext highlighter-rouge">rewrite</code> phase.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc29</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_transform_underscores_in_response_headers">lua_transform_underscores_in_response_headers</h2>
<table>
<tbody>
<tr>
<td><strong>syntax:</strong> *lua_transform_underscores_in_response_headers on</td>
<td>off*</td>
</tr>
</tbody>
</table>
<p><strong>default:</strong> <em>lua_transform_underscores_in_response_headers on</em></p>
<p><strong>context:</strong> <em>http, server, location, location-if</em></p>
<p>Controls whether to transform underscores (<code class="language-plaintext highlighter-rouge">_</code>) in the response header names specified in the <a href="#ngxheaderheader">ngx.header.HEADER</a> API to hypens (<code class="language-plaintext highlighter-rouge">-</code>).</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc32</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_check_client_abort">lua_check_client_abort</h2>
<table>
<tbody>
<tr>
<td><strong>syntax:</strong> *lua_check_client_abort on</td>
<td>off*</td>
</tr>
</tbody>
</table>
<p><strong>default:</strong> <em>lua_check_client_abort off</em></p>
<p><strong>context:</strong> <em>http, server, location, location-if</em></p>
<p>This directive controls whether to check for premature client connection abortion.</p>
<p>When this directive is turned on, the ngx_lua module will monitor the premature connection close event on the downstream connections. And when there is such an event, it will call the user Lua function callback (registered by <a href="#ngxon_abort">ngx.on_abort</a>) or just stop and clean up all the Lua “light threads” running in the current requests request handler when there is no user callback function registered.</p>
<p>According to the current implementation, however, if the client closes the connection before the Lua code finishes reading the request body data via <a href="#ngxreqsocket">ngx.req.socket</a>, then ngx_lua will neither stop all the running “light threads” nor call the user callback (if <a href="#ngxon_abort">ngx.on_abort</a> has been called). Instead, the reading operation on <a href="#ngxreqsocket">ngx.req.socket</a> will just return the error message “client aborted” as the second return value (the first return value is surely <code class="language-plaintext highlighter-rouge">nil</code>).</p>
<p>When TCP keepalive is disabled, it is relying on the client side to close the socket gracefully (by sending a <code class="language-plaintext highlighter-rouge">FIN</code> packet or something like that). For (soft) real-time web applications, it is highly recommended to configure the <a href="http://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html">TCP keepalive</a> support in your systems TCP stack implementation in order to detect “half-open” TCP connections in time.</p>
<p>For example, on Linux, you can configure the standard <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#listen">listen</a> directive in your <code class="language-plaintext highlighter-rouge">nginx.conf</code> file like this:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">listen</span> <span class="mi">80</span> <span class="s">so_keepalive=2s:2s:8</span><span class="p">;</span>
</code></pre></div></div>
<p>On FreeBSD, you can only tune the system-wide configuration for TCP keepalive, for example:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># sysctl net.inet.tcp.keepintvl=2000
# sysctl net.inet.tcp.keepidle=2000
</code></pre></div></div>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.7.4</code> release.</p>
<p>See also <a href="#ngxon_abort">ngx.on_abort</a>.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_max_pending_timers">lua_max_pending_timers</h2>
<p><strong>syntax:</strong> <em>lua_max_pending_timers &lt;count&gt;</em></p>
<p><strong>default:</strong> <em>lua_max_pending_timers 1024</em></p>
<p><strong>context:</strong> <em>http</em></p>
<p>Controls the maximum number of pending timers allowed.</p>
<p>Pending timers are those timers that have not expired yet.</p>
<p>When exceeding this limit, the <a href="#ngxtimerat">ngx.timer.at</a> call will immediately return <code class="language-plaintext highlighter-rouge">nil</code> and the error string “too many pending timers”.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.8.0</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h2 id="lua_max_running_timers">lua_max_running_timers</h2>
<p><strong>syntax:</strong> <em>lua_max_running_timers &lt;count&gt;</em></p>
<p><strong>default:</strong> <em>lua_max_running_timers 256</em></p>
<p><strong>context:</strong> <em>http</em></p>
<p>Controls the maximum number of “running timers” allowed.</p>
<p>Running timers are those timers whose user callback functions are still running.</p>
<p>When exceeding this limit, Nginx will stop running the callbacks of newly expired timers and log an error message “N lua_max_running_timers are not enough” where “N” is the current value of this directive.</p>
<p>This directive was first introduced in the <code class="language-plaintext highlighter-rouge">v0.8.0</code> release.</p>
<p><a href="#directives">Back to TOC</a></p>
<h1 id="nginx-api-for-lua">Nginx API for Lua</h1>
<ul>
<li><a href="#introduction">Introduction</a></li>
<li><a href="#ngxarg">ngx.arg</a></li>
<li><a href="#ngxvarvariable">ngx.var.VARIABLE</a></li>
<li><a href="#core-constants">Core constants</a></li>
<li><a href="#http-method-constants">HTTP method constants</a></li>
<li><a href="#http-status-constants">HTTP status constants</a></li>
<li><a href="#nginx-log-level-constants">Nginx log level constants</a></li>
<li><a href="#print">print</a></li>
<li><a href="#ngxctx">ngx.ctx</a></li>
<li><a href="#ngxlocationcapture">ngx.location.capture</a></li>
<li><a href="#ngxlocationcapture_multi">ngx.location.capture_multi</a></li>
<li><a href="#ngxstatus">ngx.status</a></li>
<li><a href="#ngxheaderheader">ngx.header.HEADER</a></li>
<li><a href="#ngxrespget_headers">ngx.resp.get_headers</a></li>
<li><a href="#ngxreqstart_time">ngx.req.start_time</a></li>
<li><a href="#ngxreqhttp_version">ngx.req.http_version</a></li>
<li><a href="#ngxreqraw_header">ngx.req.raw_header</a></li>
<li><a href="#ngxreqget_method">ngx.req.get_method</a></li>
<li><a href="#ngxreqset_method">ngx.req.set_method</a></li>
<li><a href="#ngxreqset_uri">ngx.req.set_uri</a></li>
<li><a href="#ngxreqset_uri_args">ngx.req.set_uri_args</a></li>
<li><a href="#ngxreqget_uri_args">ngx.req.get_uri_args</a></li>
<li><a href="#ngxreqget_post_args">ngx.req.get_post_args</a></li>
<li><a href="#ngxreqget_headers">ngx.req.get_headers</a></li>
<li><a href="#ngxreqset_header">ngx.req.set_header</a></li>
<li><a href="#ngxreqclear_header">ngx.req.clear_header</a></li>
<li><a href="#ngxreqread_body">ngx.req.read_body</a></li>
<li><a href="#ngxreqdiscard_body">ngx.req.discard_body</a></li>
<li><a href="#ngxreqget_body_data">ngx.req.get_body_data</a></li>
<li><a href="#ngxreqget_body_file">ngx.req.get_body_file</a></li>
<li><a href="#ngxreqset_body_data">ngx.req.set_body_data</a></li>
<li><a href="#ngxreqset_body_file">ngx.req.set_body_file</a></li>
<li><a href="#ngxreqinit_body">ngx.req.init_body</a></li>
<li><a href="#ngxreqappend_body">ngx.req.append_body</a></li>
<li><a href="#ngxreqfinish_body">ngx.req.finish_body</a></li>
<li><a href="#ngxreqsocket">ngx.req.socket</a></li>
<li><a href="#ngxexec">ngx.exec</a></li>
<li><a href="#ngxredirect">ngx.redirect</a></li>
<li><a href="#ngxsend_headers">ngx.send_headers</a></li>
<li><a href="#ngxheaders_sent">ngx.headers_sent</a></li>
<li><a href="#ngxprint">ngx.print</a></li>
<li><a href="#ngxsay">ngx.say</a></li>
<li><a href="#ngxlog">ngx.log</a></li>
<li><a href="#ngxflush">ngx.flush</a></li>
<li><a href="#ngxexit">ngx.exit</a></li>
<li><a href="#ngxeof">ngx.eof</a></li>
<li><a href="#ngxsleep">ngx.sleep</a></li>
<li><a href="#ngxescape_uri">ngx.escape_uri</a></li>
<li><a href="#ngxunescape_uri">ngx.unescape_uri</a></li>
<li><a href="#ngxencode_args">ngx.encode_args</a></li>
<li><a href="#ngxdecode_args">ngx.decode_args</a></li>
<li><a href="#ngxencode_base64">ngx.encode_base64</a></li>
<li><a href="#ngxdecode_base64">ngx.decode_base64</a></li>
<li><a href="#ngxcrc32_short">ngx.crc32_short</a></li>
<li><a href="#ngxcrc32_long">ngx.crc32_long</a></li>
<li><a href="#ngxhmac_sha1">ngx.hmac_sha1</a></li>
<li><a href="#ngxmd5">ngx.md5</a></li>
<li><a href="#ngxmd5_bin">ngx.md5_bin</a></li>
<li><a href="#ngxsha1_bin">ngx.sha1_bin</a></li>
<li><a href="#ngxquote_sql_str">ngx.quote_sql_str</a></li>
<li><a href="#ngxtoday">ngx.today</a></li>
<li><a href="#ngxtime">ngx.time</a></li>
<li><a href="#ngxnow">ngx.now</a></li>
<li><a href="#ngxupdate_time">ngx.update_time</a></li>
<li><a href="#ngxlocaltime">ngx.localtime</a></li>
<li><a href="#ngxutctime">ngx.utctime</a></li>
<li><a href="#ngxcookie_time">ngx.cookie_time</a></li>
<li><a href="#ngxhttp_time">ngx.http_time</a></li>
<li><a href="#ngxparse_http_time">ngx.parse_http_time</a></li>
<li><a href="#ngxis_subrequest">ngx.is_subrequest</a></li>
<li><a href="#ngxrematch">ngx.re.match</a></li>
<li><a href="#ngxrefind">ngx.re.find</a></li>
<li><a href="#ngxregmatch">ngx.re.gmatch</a></li>
<li><a href="#ngxresub">ngx.re.sub</a></li>
<li><a href="#ngxregsub">ngx.re.gsub</a></li>
<li><a href="#ngxshareddict">ngx.shared.DICT</a></li>
<li><a href="#ngxshareddictget">ngx.shared.DICT.get</a></li>
<li><a href="#ngxshareddictget_stale">ngx.shared.DICT.get_stale</a></li>
<li><a href="#ngxshareddictset">ngx.shared.DICT.set</a></li>
<li><a href="#ngxshareddictsafe_set">ngx.shared.DICT.safe_set</a></li>
<li><a href="#ngxshareddictadd">ngx.shared.DICT.add</a></li>
<li><a href="#ngxshareddictsafe_add">ngx.shared.DICT.safe_add</a></li>
<li><a href="#ngxshareddictreplace">ngx.shared.DICT.replace</a></li>
<li><a href="#ngxshareddictdelete">ngx.shared.DICT.delete</a></li>
<li><a href="#ngxshareddictincr">ngx.shared.DICT.incr</a></li>
<li><a href="#ngxshareddictflush_all">ngx.shared.DICT.flush_all</a></li>
<li><a href="#ngxshareddictflush_expired">ngx.shared.DICT.flush_expired</a></li>
<li><a href="#ngxshareddictget_keys">ngx.shared.DICT.get_keys</a></li>
<li><a href="#ngxsocketudp">ngx.socket.udp</a></li>
<li><a href="#udpsocksetpeername">udpsock:setpeername</a></li>
<li><a href="#udpsocksend">udpsock:send</a></li>
<li><a href="#udpsockreceive">udpsock:receive</a></li>
<li><a href="#udpsockclose">udpsock:close</a></li>
<li><a href="#udpsocksettimeout">udpsock:settimeout</a></li>
<li><a href="#ngxsockettcp">ngx.socket.tcp</a></li>
<li><a href="#tcpsockconnect">tcpsock:connect</a></li>
<li><a href="#tcpsocksslhandshake">tcpsock:sslhandshake</a></li>
<li><a href="#tcpsocksend">tcpsock:send</a></li>
<li><a href="#tcpsockreceive">tcpsock:receive</a></li>
<li><a href="#tcpsockreceiveuntil">tcpsock:receiveuntil</a></li>
<li><a href="#tcpsockclose">tcpsock:close</a></li>
<li><a href="#tcpsocksettimeout">tcpsock:settimeout</a></li>
<li><a href="#tcpsocksetoption">tcpsock:setoption</a></li>
<li><a href="#tcpsocksetkeepalive">tcpsock:setkeepalive</a></li>
<li><a href="#tcpsockgetreusedtimes">tcpsock:getreusedtimes</a></li>
<li><a href="#ngxsocketconnect">ngx.socket.connect</a></li>
<li><a href="#ngxget_phase">ngx.get_phase</a></li>
<li><a href="#ngxthreadspawn">ngx.thread.spawn</a></li>
<li><a href="#ngxthreadwait">ngx.thread.wait</a></li>
<li><a href="#ngxthreadkill">ngx.thread.kill</a></li>
<li><a href="#ngxon_abort">ngx.on_abort</a></li>
<li><a href="#ngxtimerat">ngx.timer.at</a></li>
<li><a href="#ngxconfigdebug">ngx.config.debug</a></li>
<li><a href="#ngxconfigprefix">ngx.config.prefix</a></li>
<li><a href="#ngxconfignginx_version">ngx.config.nginx_version</a></li>
<li><a href="#ngxconfignginx_configure">ngx.config.nginx_configure</a></li>
<li><a href="#ngxconfigngx_lua_version">ngx.config.ngx_lua_version</a></li>
<li><a href="#ngxworkerexiting">ngx.worker.exiting</a></li>
<li><a href="#ngxworkerpid">ngx.worker.pid</a></li>
<li><a href="#ndkset_vardirective">ndk.set_var.DIRECTIVE</a></li>
<li><a href="#coroutinecreate">coroutine.create</a></li>
<li><a href="#coroutineresume">coroutine.resume</a></li>
<li><a href="#coroutineyield">coroutine.yield</a></li>
<li><a href="#coroutinewrap">coroutine.wrap</a></li>
<li><a href="#coroutinerunning">coroutine.running</a></li>
<li><a href="#coroutinestatus">coroutine.status</a></li>
</ul>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h2 id="introduction">Introduction</h2>
<p>The various <code class="language-plaintext highlighter-rouge">*_by_lua</code> and <code class="language-plaintext highlighter-rouge">*_by_lua_file</code> configuration directives serve as gateways to the Lua API within the <code class="language-plaintext highlighter-rouge">nginx.conf</code> file. The Nginx Lua API described below can only be called within the user Lua code run in the context of these configuration directives.</p>
<p>The API is exposed to Lua in the form of two standard packages <code class="language-plaintext highlighter-rouge">ngx</code> and <code class="language-plaintext highlighter-rouge">ndk</code>. These packages are in the default global scope within ngx_lua and are always available within ngx_lua directives.</p>
<p>The packages can be introduced into external Lua modules like this:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">say</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">say</span>
<span class="kd">local</span> <span class="n">_M</span> <span class="o">=</span> <span class="p">{}</span>
<span class="k">function</span> <span class="nc">_M</span><span class="p">.</span><span class="nf">foo</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="n">say</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">return</span> <span class="n">_M</span>
</code></pre></div></div>
<p>Use of the <a href="http://www.lua.org/manual/5.1/manual.html#pdf-package.seeall">package.seeall</a> flag is strongly discouraged due to its various bad side-effects.</p>
<p>It is also possible to directly require the packages in external Lua modules:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">ngx</span> <span class="o">=</span> <span class="nb">require</span> <span class="s2">"ngx"</span>
<span class="kd">local</span> <span class="n">ndk</span> <span class="o">=</span> <span class="nb">require</span> <span class="s2">"ndk"</span>
</code></pre></div></div>
<p>The ability to require these packages was introduced in the <code class="language-plaintext highlighter-rouge">v0.2.1rc19</code> release.</p>
<p>Network I/O operations in user code should only be done through the Nginx Lua API calls as the Nginx event loop may be blocked and performance drop off dramatically otherwise. Disk operations with relatively small amount of data can be done using the standard Lua <code class="language-plaintext highlighter-rouge">io</code> library but huge file reading and writing should be avoided wherever possible as they may block the Nginx process significantly. Delegating all network and disk I/O operations to Nginxs subrequests (via the <a href="#ngxlocationcapture">ngx.location.capture</a> method and similar) is strongly recommended for maximum performance.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxarg">ngx.arg</h2>
<p><strong>syntax:</strong> <em>val = ngx.arg[index]</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, body_filter_by_lua**</p>
<p>When this is used in the context of the <a href="#set_by_lua">set_by_lua</a> or <a href="#set_by_lua_file">set_by_lua_file</a> directives, this table is read-only and holds the input arguments to the config directives:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">value</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">arg</span><span class="p">[</span><span class="n">n</span><span class="p">]</span>
</code></pre></div></div>
<p>Here is an example</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/foo</span> <span class="p">{</span>
<span class="kn">set</span> <span class="nv">$a</span> <span class="mi">32</span><span class="p">;</span>
<span class="kn">set</span> <span class="nv">$b</span> <span class="mi">56</span><span class="p">;</span>
<span class="kn">set_by_lua</span> <span class="nv">$sum</span>
<span class="s">'return</span> <span class="s">tonumber(ngx.arg[1])</span> <span class="s">+</span> <span class="s">tonumber(ngx.arg[2])'</span>
<span class="nv">$a</span> <span class="nv">$b</span><span class="p">;</span>
<span class="kn">echo</span> <span class="nv">$sum</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>that writes out <code class="language-plaintext highlighter-rouge">88</code>, the sum of <code class="language-plaintext highlighter-rouge">32</code> and <code class="language-plaintext highlighter-rouge">56</code>.</p>
<p>When this table is used in the context of <a href="#body_filter_by_lua">body_filter_by_lua</a> or <a href="#body_filter_by_lua_file">body_filter_by_lua_file</a>, the first element holds the input data chunk to the output filter code and the second element holds the boolean flag for the “eof” flag indicating the end of the whole output data stream.</p>
<p>The data chunk and “eof” flag passed to the downstream Nginx output filters can also be overridden by assigning values directly to the corresponding table elements. When setting <code class="language-plaintext highlighter-rouge">nil</code> or an empty Lua string value to <code class="language-plaintext highlighter-rouge">ngx.arg[1]</code>, no data chunk will be passed to the downstream Nginx output filters at all.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxvarvariable">ngx.var.VARIABLE</h2>
<p><strong>syntax:</strong> <em>ngx.var.VAR_NAME</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua*, log_by_lua**</p>
<p>Read and write Nginx variable values.</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">value</span> <span class="p">=</span> <span class="s">ngx.var.some_nginx_variable_name</span>
<span class="s">ngx.var.some_nginx_variable_name</span> <span class="p">=</span> <span class="s">value</span>
</code></pre></div></div>
<p>Note that only already defined nginx variables can be written to.
For example:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/foo</span> <span class="p">{</span>
<span class="kn">set</span> <span class="nv">$my_var</span> <span class="s">''</span><span class="p">;</span> <span class="c1"># this line is required to create $my_var at config time</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">ngx.var.my_var</span> <span class="p">=</span> <span class="mi">123</span><span class="p">;</span>
<span class="kn">...</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>That is, nginx variables cannot be created on-the-fly.</p>
<p>Some special nginx variables like <code class="language-plaintext highlighter-rouge">$args</code> and <code class="language-plaintext highlighter-rouge">$limit_rate</code> can be assigned a value,
many others are not, like <code class="language-plaintext highlighter-rouge">$query_string</code>, <code class="language-plaintext highlighter-rouge">$arg_PARAMETER</code>, and <code class="language-plaintext highlighter-rouge">$http_NAME</code>.</p>
<p>Nginx regex group capturing variables <code class="language-plaintext highlighter-rouge">$1</code>, <code class="language-plaintext highlighter-rouge">$2</code>, <code class="language-plaintext highlighter-rouge">$3</code>, and etc, can be read by this
interface as well, by writing <code class="language-plaintext highlighter-rouge">ngx.var[1]</code>, <code class="language-plaintext highlighter-rouge">ngx.var[2]</code>, <code class="language-plaintext highlighter-rouge">ngx.var[3]</code>, and etc.</p>
<p>Setting <code class="language-plaintext highlighter-rouge">ngx.var.Foo</code> to a <code class="language-plaintext highlighter-rouge">nil</code> value will unset the <code class="language-plaintext highlighter-rouge">$Foo</code> Nginx variable.</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">var</span><span class="p">.</span><span class="n">args</span> <span class="o">=</span> <span class="kc">nil</span>
</code></pre></div></div>
<p><strong>WARNING</strong> When reading from an Nginx variable, Nginx will allocate memory in the per-request memory pool which is freed only at request termination. So when you need to read from an Nginx variable repeatedly in your Lua code, cache the Nginx variable value to your own Lua variable, for example,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">val</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">var</span><span class="p">.</span><span class="n">some_var</span>
<span class="c1">--- use the val repeatedly later</span>
</code></pre></div></div>
<p>to prevent (temporary) memory leaking within the current requests lifetime. Another way of caching the result is to use the <a href="#ngxctx">ngx.ctx</a> table.</p>
<p>This API requires a relatively expensive metamethod call and it is recommended to avoid using it on hot code paths.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="core-constants">Core constants</h2>
<p><strong>context:</strong> <em>init_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua, *log_by_lua</em>, ngx.timer.**</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">OK</span> <span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">ERROR</span> <span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">AGAIN</span> <span class="p">(</span><span class="o">-</span><span class="mi">2</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">DONE</span> <span class="p">(</span><span class="o">-</span><span class="mi">4</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">DECLINED</span> <span class="p">(</span><span class="o">-</span><span class="mi">5</span><span class="p">)</span>
</code></pre></div></div>
<p>Note that only three of these constants are utilized by the <a href="#nginx-api-for-lua">Nginx API for Lua</a> (i.e., <a href="#ngxexit">ngx.exit</a> accepts <code class="language-plaintext highlighter-rouge">NGX_OK</code>, <code class="language-plaintext highlighter-rouge">NGX_ERROR</code>, and <code class="language-plaintext highlighter-rouge">NGX_DECLINED</code> as input).</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">null</span>
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">ngx.null</code> constant is a <code class="language-plaintext highlighter-rouge">NULL</code> light userdata usually used to represent nil values in Lua tables etc and is similar to the <a href="http://www.kyne.com.au/~mark/software/lua-cjson.php">lua-cjson</a> librarys <code class="language-plaintext highlighter-rouge">cjson.null</code> constant. This constant was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc5</code> release.</p>
<p>The <code class="language-plaintext highlighter-rouge">ngx.DECLINED</code> constant was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc19</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="http-method-constants">HTTP method constants</h2>
<p><strong>context:</strong> <em>init_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua, log_by_lua</em>, ngx.timer.**</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> ngx.HTTP_GET
ngx.HTTP_HEAD
ngx.HTTP_PUT
ngx.HTTP_POST
ngx.HTTP_DELETE
ngx.HTTP_OPTIONS (added in the v0.5.0rc24 release)
ngx.HTTP_MKCOL (added in the v0.8.2 release)
ngx.HTTP_COPY (added in the v0.8.2 release)
ngx.HTTP_MOVE (added in the v0.8.2 release)
ngx.HTTP_PROPFIND (added in the v0.8.2 release)
ngx.HTTP_PROPPATCH (added in the v0.8.2 release)
ngx.HTTP_LOCK (added in the v0.8.2 release)
ngx.HTTP_UNLOCK (added in the v0.8.2 release)
ngx.HTTP_PATCH (added in the v0.8.2 release)
ngx.HTTP_TRACE (added in the v0.8.2 release)
</code></pre></div></div>
<p>These constants are usually used in <a href="#ngxlocationcapture">ngx.location.capture</a> and <a href="#ngxlocationcapture_multi">ngx.location.capture_multi</a> method calls.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="http-status-constants">HTTP status constants</h2>
<p><strong>context:</strong> <em>init_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua, log_by_lua</em>, ngx.timer.**</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">value</span> <span class="p">=</span> <span class="s">ngx.HTTP_OK</span> <span class="s">(200)</span>
<span class="s">value</span> <span class="p">=</span> <span class="s">ngx.HTTP_CREATED</span> <span class="s">(201)</span>
<span class="s">value</span> <span class="p">=</span> <span class="s">ngx.HTTP_SPECIAL_RESPONSE</span> <span class="s">(300)</span>
<span class="s">value</span> <span class="p">=</span> <span class="s">ngx.HTTP_MOVED_PERMANENTLY</span> <span class="s">(301)</span>
<span class="s">value</span> <span class="p">=</span> <span class="s">ngx.HTTP_MOVED_TEMPORARILY</span> <span class="s">(302)</span>
<span class="s">value</span> <span class="p">=</span> <span class="s">ngx.HTTP_SEE_OTHER</span> <span class="s">(303)</span>
<span class="s">value</span> <span class="p">=</span> <span class="s">ngx.HTTP_NOT_MODIFIED</span> <span class="s">(304)</span>
<span class="s">value</span> <span class="p">=</span> <span class="s">ngx.HTTP_BAD_REQUEST</span> <span class="s">(400)</span>
<span class="s">value</span> <span class="p">=</span> <span class="s">ngx.HTTP_UNAUTHORIZED</span> <span class="s">(401)</span>
<span class="s">value</span> <span class="p">=</span> <span class="s">ngx.HTTP_FORBIDDEN</span> <span class="s">(403)</span>
<span class="s">value</span> <span class="p">=</span> <span class="s">ngx.HTTP_NOT_FOUND</span> <span class="s">(404)</span>
<span class="s">value</span> <span class="p">=</span> <span class="s">ngx.HTTP_NOT_ALLOWED</span> <span class="s">(405)</span>
<span class="s">value</span> <span class="p">=</span> <span class="s">ngx.HTTP_GONE</span> <span class="s">(410)</span>
<span class="s">value</span> <span class="p">=</span> <span class="s">ngx.HTTP_INTERNAL_SERVER_ERROR</span> <span class="s">(500)</span>
<span class="s">value</span> <span class="p">=</span> <span class="s">ngx.HTTP_METHOD_NOT_IMPLEMENTED</span> <span class="s">(501)</span>
<span class="s">value</span> <span class="p">=</span> <span class="s">ngx.HTTP_SERVICE_UNAVAILABLE</span> <span class="s">(503)</span>
<span class="s">value</span> <span class="p">=</span> <span class="s">ngx.HTTP_GATEWAY_TIMEOUT</span> <span class="s">(504)</span> <span class="s">(first</span> <span class="s">added</span> <span class="s">in</span> <span class="s">the</span> <span class="s">v0.3.1rc38</span> <span class="s">release)</span>
</code></pre></div></div>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="nginx-log-level-constants">Nginx log level constants</h2>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua, log_by_lua*, ngx.timer.**</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">STDERR</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">EMERG</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">ALERT</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">CRIT</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">ERR</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">WARN</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">NOTICE</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">INFO</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">DEBUG</span>
</code></pre></div></div>
<p>These constants are usually used by the <a href="#ngxlog">ngx.log</a> method.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="print">print</h2>
<p><strong>syntax:</strong> <em>print(…)</em></p>
<p><strong>context:</strong> <em>init_by_lua</em>, init_worker_by_lua<em>, set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua, log_by_lua*, ngx.timer.**</p>
<p>Writes argument values into the nginx <code class="language-plaintext highlighter-rouge">error.log</code> file with the <code class="language-plaintext highlighter-rouge">ngx.NOTICE</code> log level.</p>
<p>It is equivalent to</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">NOTICE</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
</code></pre></div></div>
<p>Lua <code class="language-plaintext highlighter-rouge">nil</code> arguments are accepted and result in literal <code class="language-plaintext highlighter-rouge">"nil"</code> strings while Lua booleans result in literal <code class="language-plaintext highlighter-rouge">"true"</code> or <code class="language-plaintext highlighter-rouge">"false"</code> strings. And the <code class="language-plaintext highlighter-rouge">ngx.null</code> constant will yield the <code class="language-plaintext highlighter-rouge">"null"</code> string output.</p>
<p>There is a hard coded <code class="language-plaintext highlighter-rouge">2048</code> byte limitation on error message lengths in the Nginx core. This limit includes trailing newlines and leading time stamps. If the message size exceeds this limit, Nginx will truncate the message text accordingly. This limit can be manually modified by editing the <code class="language-plaintext highlighter-rouge">NGX_MAX_ERROR_STR</code> macro definition in the <code class="language-plaintext highlighter-rouge">src/core/ngx_log.h</code> file in the Nginx source tree.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxctx">ngx.ctx</h2>
<p><strong>context:</strong> <em>init_worker_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua, log_by_lua</em>, ngx.timer.**</p>
<p>This table can be used to store per-request Lua context data and has a life time identical to the current request (as with the Nginx variables).</p>
<p>Consider the following example,</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/test</span> <span class="p">{</span>
<span class="kn">rewrite_by_lua</span> <span class="s">'</span>
<span class="s">ngx.ctx.foo</span> <span class="p">=</span> <span class="mi">76</span>
<span class="s">'</span><span class="p">;</span>
<span class="kn">access_by_lua</span> <span class="s">'</span>
<span class="s">ngx.ctx.foo</span> <span class="p">=</span> <span class="s">ngx.ctx.foo</span> <span class="s">+</span> <span class="mi">3</span>
<span class="s">'</span><span class="p">;</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">ngx.say(ngx.ctx.foo)</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Then <code class="language-plaintext highlighter-rouge">GET /test</code> will yield the output</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
79
</code></pre></div></div>
<p>That is, the <code class="language-plaintext highlighter-rouge">ngx.ctx.foo</code> entry persists across the rewrite, access, and content phases of a request.</p>
<p>Every request, including subrequests, has its own copy of the table. For example:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/sub</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">ngx.say("sub</span> <span class="s">pre:</span> <span class="s">",</span> <span class="s">ngx.ctx.blah)</span>
<span class="s">ngx.ctx.blah</span> <span class="p">=</span> <span class="mi">32</span>
<span class="s">ngx.say("sub</span> <span class="s">post:</span> <span class="s">",</span> <span class="s">ngx.ctx.blah)</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">location</span> <span class="n">/main</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">ngx.ctx.blah</span> <span class="p">=</span> <span class="mi">73</span>
<span class="s">ngx.say("main</span> <span class="s">pre:</span> <span class="s">",</span> <span class="s">ngx.ctx.blah)</span>
<span class="s">local</span> <span class="s">res</span> <span class="p">=</span> <span class="s">ngx.location.capture("/sub")</span>
<span class="s">ngx.print(res.body)</span>
<span class="s">ngx.say("main</span> <span class="s">post:</span> <span class="s">",</span> <span class="s">ngx.ctx.blah)</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Then <code class="language-plaintext highlighter-rouge">GET /main</code> will give the output</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
main pre: 73
sub pre: nil
sub post: 32
main post: 73
</code></pre></div></div>
<p>Here, modification of the <code class="language-plaintext highlighter-rouge">ngx.ctx.blah</code> entry in the subrequest does not affect the one in the parent request. This is because they have two separate versions of <code class="language-plaintext highlighter-rouge">ngx.ctx.blah</code>.</p>
<p>Internal redirection will destroy the original request <code class="language-plaintext highlighter-rouge">ngx.ctx</code> data (if any) and the new request will have an empty <code class="language-plaintext highlighter-rouge">ngx.ctx</code> table. For instance,</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/new</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">ngx.say(ngx.ctx.foo)</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">location</span> <span class="n">/orig</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">ngx.ctx.foo</span> <span class="p">=</span> <span class="s">"hello"</span>
<span class="s">ngx.exec("/new")</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Then <code class="language-plaintext highlighter-rouge">GET /orig</code> will give</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
nil
</code></pre></div></div>
<p>rather than the original <code class="language-plaintext highlighter-rouge">"hello"</code> value.</p>
<p>Arbitrary data values, including Lua closures and nested tables, can be inserted into this “magic” table. It also allows the registration of custom meta methods.</p>
<p>Overriding <code class="language-plaintext highlighter-rouge">ngx.ctx</code> with a new Lua table is also supported, for example,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">ctx</span> <span class="o">=</span> <span class="p">{</span> <span class="n">foo</span> <span class="o">=</span> <span class="mi">32</span><span class="p">,</span> <span class="n">bar</span> <span class="o">=</span> <span class="mi">54</span> <span class="p">}</span>
</code></pre></div></div>
<p>When being used in the context of <a href="#init_worker_by_lua">init_worker_by_lua*</a>, this table just has the same lifetime of the current Lua handler.</p>
<p>The <code class="language-plaintext highlighter-rouge">ngx.ctx</code> lookup requires relatively expensive metamethod calls and it is much slower than explicitly passing per-request data along by your own function arguments. So do not abuse this API for saving your own function arguments because it usually has quite some performance impact. And because of the metamethod magic, never “local” the <code class="language-plaintext highlighter-rouge">ngx.ctx</code> table outside your function scope.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxlocationcapture">ngx.location.capture</h2>
<p><strong>syntax:</strong> <em>res = ngx.location.capture(uri, options?)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua*, content_by_lua**</p>
<p>Issue a synchronous but still non-blocking <em>Nginx Subrequest</em> using <code class="language-plaintext highlighter-rouge">uri</code>.</p>
<p>Nginxs subrequests provide a powerful way to make non-blocking internal requests to other locations configured with disk file directory or <em>any</em> other nginx C modules like <code class="language-plaintext highlighter-rouge">ngx_proxy</code>, <code class="language-plaintext highlighter-rouge">ngx_fastcgi</code>, <code class="language-plaintext highlighter-rouge">ngx_memc</code>,
<code class="language-plaintext highlighter-rouge">ngx_postgres</code>, <code class="language-plaintext highlighter-rouge">ngx_drizzle</code>, and even ngx_lua itself and etc etc etc.</p>
<p>Also note that subrequests just mimic the HTTP interface but there is <em>no</em> extra HTTP/TCP traffic <em>nor</em> IPC involved. Everything works internally, efficiently, on the C level.</p>
<p>Subrequests are completely different from HTTP 301/302 redirection (via <a href="#ngxredirect">ngx.redirect</a>) and internal redirection (via <a href="#ngxexec">ngx.exec</a>).</p>
<p>You should always read the request body (by either calling <a href="#ngxreqread_body">ngx.req.read_body</a> or configuring <a href="#lua_need_request_body">lua_need_request_body</a> on) before initiating a subrequest.</p>
<p>Here is a basic example:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">res</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">location</span><span class="p">.</span><span class="n">capture</span><span class="p">(</span><span class="n">uri</span><span class="p">)</span>
</code></pre></div></div>
<p>Returns a Lua table with 4 slots: <code class="language-plaintext highlighter-rouge">res.status</code>, <code class="language-plaintext highlighter-rouge">res.header</code>, <code class="language-plaintext highlighter-rouge">res.body</code>, and <code class="language-plaintext highlighter-rouge">res.truncated</code>.</p>
<p><code class="language-plaintext highlighter-rouge">res.status</code> holds the response status code for the subrequest response.</p>
<p><code class="language-plaintext highlighter-rouge">res.header</code> holds all the response headers of the
subrequest and it is a normal Lua table. For multi-value response headers,
the value is a Lua (array) table that holds all the values in the order that
they appear. For instance, if the subrequest response headers contain the following
lines:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
Set-Cookie: <span class="nv">a</span><span class="o">=</span>3
Set-Cookie: <span class="nv">foo</span><span class="o">=</span>bar
Set-Cookie: <span class="nv">baz</span><span class="o">=</span>blah
</code></pre></div></div>
<p>Then <code class="language-plaintext highlighter-rouge">res.header["Set-Cookie"]</code> will be evaluated to the table value
<code class="language-plaintext highlighter-rouge">{"a=3", "foo=bar", "baz=blah"}</code>.</p>
<p><code class="language-plaintext highlighter-rouge">res.body</code> holds the subrequests response body data, which might be truncated. You always need to check the <code class="language-plaintext highlighter-rouge">res.truncated</code> boolean flag to see if <code class="language-plaintext highlighter-rouge">res.body</code> contains truncated data. The data truncation here can only be caused by those unrecoverable errors in your subrequests like the cases that the remote end aborts the connection prematurely in the middle of the response body data stream or a read timeout happens when your subrequest is receiving the response body data from the remote.</p>
<p>URI query strings can be concatenated to URI itself, for instance,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">res</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">location</span><span class="p">.</span><span class="n">capture</span><span class="p">(</span><span class="s1">'/foo/bar?a=3&amp;b=4'</span><span class="p">)</span>
</code></pre></div></div>
<p>Named locations like <code class="language-plaintext highlighter-rouge">@foo</code> are not allowed due to a limitation in
the nginx core. Use normal locations combined with the <code class="language-plaintext highlighter-rouge">internal</code> directive to
prepare internal-only locations.</p>
<p>An optional option table can be fed as the second
argument, which supports the options:</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">method</code>
specify the subrequests request method, which only accepts constants like <code class="language-plaintext highlighter-rouge">ngx.HTTP_POST</code>.</li>
<li><code class="language-plaintext highlighter-rouge">body</code>
specify the subrequests request body (string value only).</li>
<li><code class="language-plaintext highlighter-rouge">args</code>
specify the subrequests URI query arguments (both string value and Lua tables are accepted)</li>
<li><code class="language-plaintext highlighter-rouge">ctx</code>
specify a Lua table to be the <a href="#ngxctx">ngx.ctx</a> table for the subrequest. It can be the current requests <a href="#ngxctx">ngx.ctx</a> table, which effectively makes the parent and its subrequest to share exactly the same context table. This option was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc25</code> release.</li>
<li><code class="language-plaintext highlighter-rouge">vars</code>
take a Lua table which holds the values to set the specified Nginx variables in the subrequest as this options value. This option was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc31</code> release.</li>
<li><code class="language-plaintext highlighter-rouge">copy_all_vars</code>
specify whether to copy over all the Nginx variable values of the current request to the subrequest in question. modifications of the nginx variables in the subrequest will not affect the current (parent) request. This option was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc31</code> release.</li>
<li><code class="language-plaintext highlighter-rouge">share_all_vars</code>
specify whether to share all the Nginx variables of the subrequest with the current (parent) request. modifications of the Nginx variables in the subrequest will affect the current (parent) request. Enabling this option may lead to hard-to-debug issues due to bad side-effects and is considered bad and harmful. Only enable this option when you completely know what you are doing.</li>
<li><code class="language-plaintext highlighter-rouge">always_forward_body</code>
when set to true, the current (parent) requests request body will always be forwarded to the subrequest being created if the <code class="language-plaintext highlighter-rouge">body</code> option is not specified. The request body read by either <a href="#ngxreqread_body">ngx.req.read_body()</a> or <a href="#lua_need_request_body">lua_need_request_body on</a> will be directly forwarded to the subrequest without copying the whole request body data when creating the subrequest (no matter the request body data is buffered in memory buffers or temporary files). By default, this option is <code class="language-plaintext highlighter-rouge">false</code> and when the <code class="language-plaintext highlighter-rouge">body</code> option is not specified, the request body of the current (parent) request is only forwarded when the subrequest takes the <code class="language-plaintext highlighter-rouge">PUT</code> or <code class="language-plaintext highlighter-rouge">POST</code> request method.</li>
</ul>
<p>Issuing a POST subrequest, for example, can be done as follows</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">res</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">location</span><span class="p">.</span><span class="n">capture</span><span class="p">(</span>
<span class="s1">'/foo/bar'</span><span class="p">,</span>
<span class="p">{</span> <span class="n">method</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">HTTP_POST</span><span class="p">,</span> <span class="n">body</span> <span class="o">=</span> <span class="s1">'hello, world'</span> <span class="p">}</span>
<span class="p">)</span>
</code></pre></div></div>
<p>See HTTP method constants methods other than POST.
The <code class="language-plaintext highlighter-rouge">method</code> option is <code class="language-plaintext highlighter-rouge">ngx.HTTP_GET</code> by default.</p>
<p>The <code class="language-plaintext highlighter-rouge">args</code> option can specify extra URI arguments, for instance,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">location</span><span class="p">.</span><span class="n">capture</span><span class="p">(</span><span class="s1">'/foo?a=1'</span><span class="p">,</span>
<span class="p">{</span> <span class="n">args</span> <span class="o">=</span> <span class="p">{</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">3</span><span class="p">,</span> <span class="n">c</span> <span class="o">=</span> <span class="s1">':'</span> <span class="p">}</span> <span class="p">}</span>
<span class="p">)</span>
</code></pre></div></div>
<p>is equivalent to</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">location</span><span class="p">.</span><span class="n">capture</span><span class="p">(</span><span class="s1">'/foo?a=1&amp;b=3&amp;c=%3a'</span><span class="p">)</span>
</code></pre></div></div>
<p>that is, this method will escape argument keys and values according to URI rules and
concatenate them together into a complete query string. The format for the Lua table passed as the <code class="language-plaintext highlighter-rouge">args</code> argument is identical to the format used in the <a href="#ngxencode_args">ngx.encode_args</a> method.</p>
<p>The <code class="language-plaintext highlighter-rouge">args</code> option can also take plain query strings:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">location</span><span class="p">.</span><span class="n">capture</span><span class="p">(</span><span class="s1">'/foo?a=1'</span><span class="p">,</span>
<span class="p">{</span> <span class="n">args</span> <span class="o">=</span> <span class="s1">'b=3&amp;c=%3a'</span> <span class="p">}</span> <span class="p">}</span>
<span class="p">)</span>
</code></pre></div></div>
<p>This is functionally identical to the previous examples.</p>
<p>The <code class="language-plaintext highlighter-rouge">share_all_vars</code> option controls whether to share nginx variables among the current request and its subrequests.
If this option is set to <code class="language-plaintext highlighter-rouge">true</code>, then the current request and associated subrequests will share the same Nginx variable scope. Hence, changes to Nginx variables made by a subrequest will affect the current request.</p>
<p>Care should be taken in using this option as variable scope sharing can have unexpected side effects. The <code class="language-plaintext highlighter-rouge">args</code>, <code class="language-plaintext highlighter-rouge">vars</code>, or <code class="language-plaintext highlighter-rouge">copy_all_vars</code> options are generally preferable instead.</p>
<p>This option is set to <code class="language-plaintext highlighter-rouge">false</code> by default</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/other</span> <span class="p">{</span>
<span class="kn">set</span> <span class="nv">$dog</span> <span class="s">"</span><span class="nv">$dog</span> <span class="s">world"</span><span class="p">;</span>
<span class="kn">echo</span> <span class="s">"</span><span class="nv">$uri</span> <span class="s">dog:</span> <span class="nv">$dog</span><span class="s">"</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">location</span> <span class="n">/lua</span> <span class="p">{</span>
<span class="kn">set</span> <span class="nv">$dog</span> <span class="s">'hello'</span><span class="p">;</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">res</span> <span class="p">=</span> <span class="s">ngx.location.capture("/other",</span>
<span class="p">{</span> <span class="kn">share_all_vars</span> <span class="p">=</span> <span class="s">true</span> <span class="err">}</span><span class="s">)</span><span class="p">;</span>
<span class="kn">ngx.print</span><span class="s">(res.body)</span>
<span class="s">ngx.say(ngx.var.uri,</span> <span class="s">":</span> <span class="s">",</span> <span class="s">ngx.var.dog)</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Accessing location <code class="language-plaintext highlighter-rouge">/lua</code> gives</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/other dog: hello world
/lua: hello world
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">copy_all_vars</code> option provides a copy of the parent requests Nginx variables to subrequests when such subrequests are issued. Changes made to these variables by such subrequests will not affect the parent request or any other subrequests sharing the parent requests variables.</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/other</span> <span class="p">{</span>
<span class="kn">set</span> <span class="nv">$dog</span> <span class="s">"</span><span class="nv">$dog</span> <span class="s">world"</span><span class="p">;</span>
<span class="kn">echo</span> <span class="s">"</span><span class="nv">$uri</span> <span class="s">dog:</span> <span class="nv">$dog</span><span class="s">"</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">location</span> <span class="n">/lua</span> <span class="p">{</span>
<span class="kn">set</span> <span class="nv">$dog</span> <span class="s">'hello'</span><span class="p">;</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">res</span> <span class="p">=</span> <span class="s">ngx.location.capture("/other",</span>
<span class="p">{</span> <span class="kn">copy_all_vars</span> <span class="p">=</span> <span class="s">true</span> <span class="err">}</span><span class="s">)</span><span class="p">;</span>
<span class="kn">ngx.print</span><span class="s">(res.body)</span>
<span class="s">ngx.say(ngx.var.uri,</span> <span class="s">":</span> <span class="s">",</span> <span class="s">ngx.var.dog)</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Request <code class="language-plaintext highlighter-rouge">GET /lua</code> will give the output</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/other dog: hello world
/lua: hello
</code></pre></div></div>
<p>Note that if both <code class="language-plaintext highlighter-rouge">share_all_vars</code> and <code class="language-plaintext highlighter-rouge">copy_all_vars</code> are set to true, then <code class="language-plaintext highlighter-rouge">share_all_vars</code> takes precedence.</p>
<p>In addition to the two settings above, it is possible to specify
values for variables in the subrequest using the <code class="language-plaintext highlighter-rouge">vars</code> option. These
variables are set after the sharing or copying of variables has been
evaluated, and provides a more efficient method of passing specific
values to a subrequest over encoding them as URL arguments and
unescaping them in the Nginx config file.</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/other</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">ngx.say("dog</span> <span class="p">=</span> <span class="s">",</span> <span class="s">ngx.var.dog)</span>
<span class="s">ngx.say("cat</span> <span class="p">=</span> <span class="s">",</span> <span class="s">ngx.var.cat)</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">location</span> <span class="n">/lua</span> <span class="p">{</span>
<span class="kn">set</span> <span class="nv">$dog</span> <span class="s">''</span><span class="p">;</span>
<span class="kn">set</span> <span class="nv">$cat</span> <span class="s">''</span><span class="p">;</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">res</span> <span class="p">=</span> <span class="s">ngx.location.capture("/other",</span>
<span class="p">{</span> <span class="kn">vars</span> <span class="p">=</span> <span class="p">{</span> <span class="kn">dog</span> <span class="p">=</span> <span class="s">"hello",</span> <span class="s">cat</span> <span class="p">=</span> <span class="mi">32</span> <span class="err">}}</span><span class="s">)</span><span class="p">;</span>
<span class="kn">ngx.print</span><span class="s">(res.body)</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Accessing <code class="language-plaintext highlighter-rouge">/lua</code> will yield the output</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>dog = hello
cat = 32
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">ctx</code> option can be used to specify a custom Lua table to serve as the <a href="#ngxctx">ngx.ctx</a> table for the subrequest.</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/sub</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">ngx.ctx.foo</span> <span class="p">=</span> <span class="s">"bar"</span><span class="p">;</span>
<span class="kn">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">location</span> <span class="n">/lua</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">ctx</span> <span class="p">=</span> <span class="p">{}</span>
<span class="kn">res</span> <span class="p">=</span> <span class="s">ngx.location.capture("/sub",</span> <span class="p">{</span> <span class="kn">ctx</span> <span class="p">=</span> <span class="s">ctx</span> <span class="err">}</span><span class="s">)</span>
<span class="s">ngx.say(ctx.foo)</span><span class="p">;</span>
<span class="kn">ngx.say</span><span class="s">(ngx.ctx.foo)</span><span class="p">;</span>
<span class="kn">'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Then request <code class="language-plaintext highlighter-rouge">GET /lua</code> gives</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>bar
nil
</code></pre></div></div>
<p>It is also possible to use this <code class="language-plaintext highlighter-rouge">ctx</code> option to share the same <a href="#ngxctx">ngx.ctx</a> table between the current (parent) request and the subrequest:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/sub</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">ngx.ctx.foo</span> <span class="p">=</span> <span class="s">"bar"</span><span class="p">;</span>
<span class="kn">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">location</span> <span class="n">/lua</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">res</span> <span class="p">=</span> <span class="s">ngx.location.capture("/sub",</span> <span class="p">{</span> <span class="kn">ctx</span> <span class="p">=</span> <span class="s">ngx.ctx</span> <span class="err">}</span><span class="s">)</span>
<span class="s">ngx.say(ngx.ctx.foo)</span><span class="p">;</span>
<span class="kn">'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Request <code class="language-plaintext highlighter-rouge">GET /lua</code> yields the output</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>bar
</code></pre></div></div>
<p>Note that subrequests issued by <a href="#ngxlocationcapture">ngx.location.capture</a> inherit all the
request headers of the current request by default and that this may have unexpected side effects on the
subrequest responses. For example, when using the standard <code class="language-plaintext highlighter-rouge">ngx_proxy</code> module to serve
subrequests, an “Accept-Encoding: gzip” header in the main request may result
in gzipped responses that cannot be handled properly in Lua code. Original request headers should be ignored by setting
<a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass_request_headers">proxy_pass_request_headers</a> to <code class="language-plaintext highlighter-rouge">off</code> in subrequest locations.</p>
<p>When the <code class="language-plaintext highlighter-rouge">body</code> option is not specified and the <code class="language-plaintext highlighter-rouge">always_forward_body</code> option is false (the default value), the <code class="language-plaintext highlighter-rouge">POST</code> and <code class="language-plaintext highlighter-rouge">PUT</code> subrequests will inherit the request bodies of the parent request (if any).</p>
<p>There is a hard-coded upper limit on the number of concurrent subrequests possible for every main request. In older versions of Nginx, the limit was <code class="language-plaintext highlighter-rouge">50</code> concurrent subrequests and in more recent versions, Nginx <code class="language-plaintext highlighter-rouge">1.1.x</code> onwards, this was increased to <code class="language-plaintext highlighter-rouge">200</code> concurrent subrequests. When this limit is exceeded, the following error message is added to the <code class="language-plaintext highlighter-rouge">error.log</code> file:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[error] 13983#0: *1 subrequests cycle while processing "/uri"
</code></pre></div></div>
<p>The limit can be manually modified if required by editing the definition of the <code class="language-plaintext highlighter-rouge">NGX_HTTP_MAX_SUBREQUESTS</code> macro in the <code class="language-plaintext highlighter-rouge">nginx/src/http/ngx_http_request.h</code> file in the Nginx source tree.</p>
<p>Please also refer to restrictions on capturing locations configured by <a href="#locations-configured-by-subrequest-directives-of-other-modules">subrequest directives of other modules</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxlocationcapture_multi">ngx.location.capture_multi</h2>
<p><strong>syntax:</strong> <em>res1, res2, … = ngx.location.capture_multi({ {uri, options?}, {uri, options?}, … })</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua*, content_by_lua**</p>
<p>Just like <a href="#ngxlocationcapture">ngx.location.capture</a>, but supports multiple subrequests running in parallel.</p>
<p>This function issues several parallel subrequests specified by the input table and returns their results in the same order. For example,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">res1</span><span class="p">,</span> <span class="n">res2</span><span class="p">,</span> <span class="n">res3</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">location</span><span class="p">.</span><span class="n">capture_multi</span><span class="p">{</span>
<span class="p">{</span> <span class="s2">"/foo"</span><span class="p">,</span> <span class="p">{</span> <span class="n">args</span> <span class="o">=</span> <span class="s2">"a=3&amp;b=4"</span> <span class="p">}</span> <span class="p">},</span>
<span class="p">{</span> <span class="s2">"/bar"</span> <span class="p">},</span>
<span class="p">{</span> <span class="s2">"/baz"</span><span class="p">,</span> <span class="p">{</span> <span class="n">method</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">HTTP_POST</span><span class="p">,</span> <span class="n">body</span> <span class="o">=</span> <span class="s2">"hello"</span> <span class="p">}</span> <span class="p">},</span>
<span class="p">}</span>
<span class="k">if</span> <span class="n">res1</span><span class="p">.</span><span class="n">status</span> <span class="o">==</span> <span class="n">ngx</span><span class="p">.</span><span class="n">HTTP_OK</span> <span class="k">then</span>
<span class="o">...</span>
<span class="k">end</span>
<span class="k">if</span> <span class="n">res2</span><span class="p">.</span><span class="n">body</span> <span class="o">==</span> <span class="s2">"BLAH"</span> <span class="k">then</span>
<span class="o">...</span>
<span class="k">end</span>
</code></pre></div></div>
<p>This function will not return until all the subrequests terminate.
The total latency is the longest latency of the individual subrequests rather than the sum.</p>
<p>Lua tables can be used for both requests and responses when the number of subrequests to be issued is not known in advance:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="c1">-- construct the requests table</span>
<span class="kd">local</span> <span class="n">reqs</span> <span class="o">=</span> <span class="p">{}</span>
<span class="nb">table.insert</span><span class="p">(</span><span class="n">reqs</span><span class="p">,</span> <span class="p">{</span> <span class="s2">"/mysql"</span> <span class="p">})</span>
<span class="nb">table.insert</span><span class="p">(</span><span class="n">reqs</span><span class="p">,</span> <span class="p">{</span> <span class="s2">"/postgres"</span> <span class="p">})</span>
<span class="nb">table.insert</span><span class="p">(</span><span class="n">reqs</span><span class="p">,</span> <span class="p">{</span> <span class="s2">"/redis"</span> <span class="p">})</span>
<span class="nb">table.insert</span><span class="p">(</span><span class="n">reqs</span><span class="p">,</span> <span class="p">{</span> <span class="s2">"/memcached"</span> <span class="p">})</span>
<span class="c1">-- issue all the requests at once and wait until they all return</span>
<span class="kd">local</span> <span class="n">resps</span> <span class="o">=</span> <span class="p">{</span> <span class="n">ngx</span><span class="p">.</span><span class="n">location</span><span class="p">.</span><span class="n">capture_multi</span><span class="p">(</span><span class="n">reqs</span><span class="p">)</span> <span class="p">}</span>
<span class="c1">-- loop over the responses table</span>
<span class="k">for</span> <span class="n">i</span><span class="p">,</span> <span class="n">resp</span> <span class="k">in</span> <span class="nb">ipairs</span><span class="p">(</span><span class="n">resps</span><span class="p">)</span> <span class="k">do</span>
<span class="c1">-- process the response table "resp"</span>
<span class="k">end</span>
</code></pre></div></div>
<p>The <a href="#ngxlocationcapture">ngx.location.capture</a> function is just a special form
of this function. Logically speaking, the <a href="#ngxlocationcapture">ngx.location.capture</a> can be implemented like this</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">location</span><span class="p">.</span><span class="n">capture</span> <span class="o">=</span>
<span class="k">function</span> <span class="p">(</span><span class="n">uri</span><span class="p">,</span> <span class="n">args</span><span class="p">)</span>
<span class="k">return</span> <span class="n">ngx</span><span class="p">.</span><span class="n">location</span><span class="p">.</span><span class="n">capture_multi</span><span class="p">({</span> <span class="p">{</span><span class="n">uri</span><span class="p">,</span> <span class="n">args</span><span class="p">}</span> <span class="p">})</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Please also refer to restrictions on capturing locations configured by <a href="#locations-configured-by-subrequest-directives-of-other-modules">subrequest directives of other modules</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxstatus">ngx.status</h2>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua, log_by_lua**</p>
<p>Read and write the current requests response status. This should be called
before sending out the response headers.</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">status</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">HTTP_CREATED</span>
<span class="n">status</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">status</span>
</code></pre></div></div>
<p>Setting <code class="language-plaintext highlighter-rouge">ngx.status</code> after the response header is sent out has no effect but leaving an error message in your nginxs error log file:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>attempt to set ngx.status after sending out response headers
</code></pre></div></div>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxheaderheader">ngx.header.HEADER</h2>
<p><strong>syntax:</strong> <em>ngx.header.HEADER = VALUE</em></p>
<p><strong>syntax:</strong> <em>value = ngx.header.HEADER</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua*, body_filter_by_lua, log_by_lua**</p>
<p>Set, add to, or clear the current requests <code class="language-plaintext highlighter-rouge">HEADER</code> response header that is to be sent.</p>
<p>Underscores (<code class="language-plaintext highlighter-rouge">_</code>) in the header names will be replaced by hyphens (<code class="language-plaintext highlighter-rouge">-</code>) by default. This transformation can be turned off via the <a href="#lua_transform_underscores_in_response_headers">lua_transform_underscores_in_response_headers</a> directive.</p>
<p>The header names are matched case-insensitively.</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="c1">-- equivalent to ngx.header["Content-Type"] = 'text/plain'</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">header</span><span class="p">.</span><span class="n">content_type</span> <span class="o">=</span> <span class="s1">'text/plain'</span><span class="p">;</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">header</span><span class="p">[</span><span class="s2">"X-My-Header"</span><span class="p">]</span> <span class="o">=</span> <span class="s1">'blah blah'</span><span class="p">;</span>
</code></pre></div></div>
<p>Multi-value headers can be set this way:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">header</span><span class="p">[</span><span class="s1">'Set-Cookie'</span><span class="p">]</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'a=32; path=/'</span><span class="p">,</span> <span class="s1">'b=4; path=/'</span><span class="p">}</span>
</code></pre></div></div>
<p>will yield</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
Set-Cookie: <span class="nv">a</span><span class="o">=</span>32<span class="p">;</span> <span class="nv">path</span><span class="o">=</span>/
Set-Cookie: <span class="nv">b</span><span class="o">=</span>4<span class="p">;</span> <span class="nv">path</span><span class="o">=</span>/
</code></pre></div></div>
<p>in the response headers.</p>
<p>Only Lua tables are accepted (Only the last element in the table will take effect for standard headers such as <code class="language-plaintext highlighter-rouge">Content-Type</code> that only accept a single value).</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">header</span><span class="p">.</span><span class="n">content_type</span> <span class="o">=</span> <span class="p">{</span><span class="s1">'a'</span><span class="p">,</span> <span class="s1">'b'</span><span class="p">}</span>
</code></pre></div></div>
<p>is equivalent to</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">header</span><span class="p">.</span><span class="n">content_type</span> <span class="o">=</span> <span class="s1">'b'</span>
</code></pre></div></div>
<p>Setting a slot to <code class="language-plaintext highlighter-rouge">nil</code> effectively removes it from the response headers:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">header</span><span class="p">[</span><span class="s2">"X-My-Header"</span><span class="p">]</span> <span class="o">=</span> <span class="kc">nil</span><span class="p">;</span>
</code></pre></div></div>
<p>The same applies to assigning an empty table:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">header</span><span class="p">[</span><span class="s2">"X-My-Header"</span><span class="p">]</span> <span class="o">=</span> <span class="p">{};</span>
</code></pre></div></div>
<p>Setting <code class="language-plaintext highlighter-rouge">ngx.header.HEADER</code> after sending out response headers (either explicitly with <a href="#ngxsend_headers">ngx.send_headers</a> or implicitly with <a href="#ngxprint">ngx.print</a> and similar) will throw out a Lua exception.</p>
<p>Reading <code class="language-plaintext highlighter-rouge">ngx.header.HEADER</code> will return the value of the response header named <code class="language-plaintext highlighter-rouge">HEADER</code>.</p>
<p>Underscores (<code class="language-plaintext highlighter-rouge">_</code>) in the header names will also be replaced by dashes (<code class="language-plaintext highlighter-rouge">-</code>) and the header names will be matched case-insensitively. If the response header is not present at all, <code class="language-plaintext highlighter-rouge">nil</code> will be returned.</p>
<p>This is particularly useful in the context of <a href="#header_filter_by_lua">header_filter_by_lua</a> and <a href="#header_filter_by_lua_file">header_filter_by_lua_file</a>, for example,</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/test</span> <span class="p">{</span>
<span class="kn">set</span> <span class="nv">$footer</span> <span class="s">''</span><span class="p">;</span>
<span class="kn">proxy_pass</span> <span class="s">http://some-backend</span><span class="p">;</span>
<span class="kn">header_filter_by_lua</span> <span class="s">'</span>
<span class="s">if</span> <span class="s">ngx.header["X-My-Header"]</span> <span class="p">==</span> <span class="s">"blah"</span> <span class="s">then</span>
<span class="s">ngx.var.footer</span> <span class="p">=</span> <span class="s">"some</span> <span class="s">value"</span>
<span class="s">end</span>
<span class="s">'</span><span class="p">;</span>
<span class="kn">echo_after_body</span> <span class="nv">$footer</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>For multi-value headers, all of the values of header will be collected in order and returned as a Lua table. For example, response headers</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Foo: bar
Foo: baz
</code></pre></div></div>
<p>will result in</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="p">{</span><span class="s2">"bar"</span><span class="p">,</span> <span class="s2">"baz"</span><span class="p">}</span>
</code></pre></div></div>
<p>to be returned when reading <code class="language-plaintext highlighter-rouge">ngx.header.Foo</code>.</p>
<p>Note that <code class="language-plaintext highlighter-rouge">ngx.header</code> is not a normal Lua table and as such, it is not possible to iterate through it using the Lua <code class="language-plaintext highlighter-rouge">ipairs</code> function.</p>
<p>For reading <em>request</em> headers, use the <a href="#ngxreqget_headers">ngx.req.get_headers</a> function instead.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxrespget_headers">ngx.resp.get_headers</h2>
<p><strong>syntax:</strong> <em>headers = ngx.resp.get_headers(max_headers?, raw?)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua, log_by_lua**</p>
<p>Returns a Lua table holding all the current response headers for the current request.</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">h</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">resp</span><span class="p">.</span><span class="n">get_headers</span><span class="p">()</span>
<span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="k">in</span> <span class="nb">pairs</span><span class="p">(</span><span class="n">h</span><span class="p">)</span> <span class="k">do</span>
<span class="o">...</span>
<span class="k">end</span>
</code></pre></div></div>
<p>This function has the same signature as <a href="#ngxreqget_headers">ngx.req.get_headers</a> except getting response headers instead of request headers.</p>
<p>This API was first introduced in the <code class="language-plaintext highlighter-rouge">v0.9.5</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqstart_time">ngx.req.start_time</h2>
<p><strong>syntax:</strong> <em>secs = ngx.req.start_time()</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua*, log_by_lua**</p>
<p>Returns a floating-point number representing the timestamp (including milliseconds as the decimal part) when the current request was created.</p>
<p>The following example emulates the <code class="language-plaintext highlighter-rouge">$request_time</code> variable value (provided by <a href="http://nginx.org/en/docs/http/ngx_http_log_module.html">ngx_http_log_module</a>) in pure Lua:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">request_time</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">now</span><span class="p">()</span> <span class="o">-</span> <span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">start_time</span><span class="p">()</span>
</code></pre></div></div>
<p>This function was first introduced in the <code class="language-plaintext highlighter-rouge">v0.7.7</code> release.</p>
<p>See also <a href="#ngxnow">ngx.now</a> and <a href="#ngxupdate_time">ngx.update_time</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqhttp_version">ngx.req.http_version</h2>
<p><strong>syntax:</strong> <em>num = ngx.req.http_version()</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua*, header_filter_by_lua**</p>
<p>Returns the HTTP version number for the current request as a Lua number.</p>
<p>Current possible values are 1.0, 1.1, and 0.9. Returns <code class="language-plaintext highlighter-rouge">nil</code> for unrecognized values.</p>
<p>This method was first introduced in the <code class="language-plaintext highlighter-rouge">v0.7.17</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqraw_header">ngx.req.raw_header</h2>
<p><strong>syntax:</strong> <em>str = ngx.req.raw_header(no_request_line?)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua*, header_filter_by_lua**</p>
<p>Returns the original raw HTTP protocol header received by the Nginx server.</p>
<p>By default, the request line and trailing <code class="language-plaintext highlighter-rouge">CR LF</code> terminator will also be included. For example,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">print</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">raw_header</span><span class="p">())</span>
</code></pre></div></div>
<p>gives something like this:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>GET /t HTTP/1.1
Host: localhost
Connection: close
Foo: bar
</code></pre></div></div>
<p>You can specify the optional
<code class="language-plaintext highlighter-rouge">no_request_line</code> argument as a <code class="language-plaintext highlighter-rouge">true</code> value to exclude the request line from the result. For example,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">print</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">raw_header</span><span class="p">(</span><span class="kc">true</span><span class="p">))</span>
</code></pre></div></div>
<p>outputs something like this:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Host: localhost
Connection: close
Foo: bar
</code></pre></div></div>
<p>This method was first introduced in the <code class="language-plaintext highlighter-rouge">v0.7.17</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqget_method">ngx.req.get_method</h2>
<p><strong>syntax:</strong> <em>method_name = ngx.req.get_method()</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua*, header_filter_by_lua**</p>
<p>Retrieves the current requests request method name. Strings like <code class="language-plaintext highlighter-rouge">"GET"</code> and <code class="language-plaintext highlighter-rouge">"POST"</code> are returned instead of numerical <a href="#http-method-constants">method constants</a>.</p>
<p>If the current request is an Nginx subrequest, then the subrequests method name will be returned.</p>
<p>This method was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.6</code> release.</p>
<p>See also <a href="#ngxreqset_method">ngx.req.set_method</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqset_method">ngx.req.set_method</h2>
<p><strong>syntax:</strong> <em>ngx.req.set_method(method_id)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua*, header_filter_by_lua**</p>
<p>Overrides the current requests request method with the <code class="language-plaintext highlighter-rouge">method_id</code> argument. Currently only numerical <a href="#http-method-constants">method constants</a> are supported, like <code class="language-plaintext highlighter-rouge">ngx.HTTP_POST</code> and <code class="language-plaintext highlighter-rouge">ngx.HTTP_GET</code>.</p>
<p>If the current request is an Nginx subrequest, then the subrequests method will be overridden.</p>
<p>This method was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.6</code> release.</p>
<p>See also <a href="#ngxreqget_method">ngx.req.get_method</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqset_uri">ngx.req.set_uri</h2>
<p><strong>syntax:</strong> <em>ngx.req.set_uri(uri, jump?)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua**</p>
<p>Rewrite the current requests (parsed) URI by the <code class="language-plaintext highlighter-rouge">uri</code> argument. The <code class="language-plaintext highlighter-rouge">uri</code> argument must be a Lua string and cannot be of zero length, or a Lua exception will be thrown.</p>
<p>The optional boolean <code class="language-plaintext highlighter-rouge">jump</code> argument can trigger location rematch (or location jump) as <a href="http://nginx.org/en/docs/http/ngx_http_rewrite_module.html">ngx_http_rewrite_module</a>s <a href="http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite">rewrite</a> directive, that is, when <code class="language-plaintext highlighter-rouge">jump</code> is <code class="language-plaintext highlighter-rouge">true</code> (default to <code class="language-plaintext highlighter-rouge">false</code>), this function will never return and it will tell Nginx to try re-searching locations with the new URI value at the later <code class="language-plaintext highlighter-rouge">post-rewrite</code> phase and jumping to the new location.</p>
<p>Location jump will not be triggered otherwise, and only the current requests URI will be modified, which is also the default behavior. This function will return but with no returned values when the <code class="language-plaintext highlighter-rouge">jump</code> argument is <code class="language-plaintext highlighter-rouge">false</code> or absent altogether.</p>
<p>For example, the following nginx config snippet</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">rewrite</span> <span class="s">^</span> <span class="n">/foo</span> <span class="s">last</span><span class="p">;</span>
</code></pre></div></div>
<p>can be coded in Lua like this:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">set_uri</span><span class="p">(</span><span class="s2">"/foo"</span><span class="p">,</span> <span class="kc">true</span><span class="p">)</span>
</code></pre></div></div>
<p>Similarly, Nginx config</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">rewrite</span> <span class="s">^</span> <span class="n">/foo</span> <span class="s">break</span><span class="p">;</span>
</code></pre></div></div>
<p>can be coded in Lua as</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">set_uri</span><span class="p">(</span><span class="s2">"/foo"</span><span class="p">,</span> <span class="kc">false</span><span class="p">)</span>
</code></pre></div></div>
<p>or equivalently,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">set_uri</span><span class="p">(</span><span class="s2">"/foo"</span><span class="p">)</span>
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">jump</code> argument can only be set to <code class="language-plaintext highlighter-rouge">true</code> in <a href="#rewrite_by_lua">rewrite_by_lua</a> and <a href="#rewrite_by_lua_file">rewrite_by_lua_file</a>. Use of jump in other contexts is prohibited and will throw out a Lua exception.</p>
<p>A more sophisticated example involving regex substitutions is as follows</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/test</span> <span class="p">{</span>
<span class="kn">rewrite_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">uri</span> <span class="p">=</span> <span class="s">ngx.re.sub(ngx.var.uri,</span> <span class="s">"^/test/(.*)",</span> <span class="s">"/</span><span class="nv">$1</span><span class="s">",</span> <span class="s">"o")</span>
<span class="s">ngx.req.set_uri(uri)</span>
<span class="s">'</span><span class="p">;</span>
<span class="kn">proxy_pass</span> <span class="s">http://my_backend</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>which is functionally equivalent to</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/test</span> <span class="p">{</span>
<span class="kn">rewrite</span> <span class="s">^/test/(.*)</span> <span class="n">/</span><span class="nv">$1</span> <span class="s">break</span><span class="p">;</span>
<span class="kn">proxy_pass</span> <span class="s">http://my_backend</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Note that it is not possible to use this interface to rewrite URI arguments and that <a href="#ngxreqset_uri_args">ngx.req.set_uri_args</a> should be used for this instead. For instance, Nginx config</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">rewrite</span> <span class="s">^</span> <span class="n">/foo?a=3?</span> <span class="s">last</span><span class="p">;</span>
</code></pre></div></div>
<p>can be coded as</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">ngx.req.set_uri_args</span><span class="s">("a=3")</span>
<span class="s">ngx.req.set_uri("/foo",</span> <span class="s">true)</span>
</code></pre></div></div>
<p>or</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">ngx.req.set_uri_args</span><span class="s">(</span><span class="p">{</span><span class="kn">a</span> <span class="p">=</span> <span class="mi">3</span><span class="err">}</span><span class="s">)</span>
<span class="s">ngx.req.set_uri("/foo",</span> <span class="s">true)</span>
</code></pre></div></div>
<p>This interface was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc14</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqset_uri_args">ngx.req.set_uri_args</h2>
<p><strong>syntax:</strong> <em>ngx.req.set_uri_args(args)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua**</p>
<p>Rewrite the current requests URI query arguments by the <code class="language-plaintext highlighter-rouge">args</code> argument. The <code class="language-plaintext highlighter-rouge">args</code> argument can be either a Lua string, as in</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">set_uri_args</span><span class="p">(</span><span class="s2">"a=3&amp;b=hello%20world"</span><span class="p">)</span>
</code></pre></div></div>
<p>or a Lua table holding the query arguments key-value pairs, as in</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">set_uri_args</span><span class="p">({</span> <span class="n">a</span> <span class="o">=</span> <span class="mi">3</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="s2">"hello world"</span> <span class="p">})</span>
</code></pre></div></div>
<p>where in the latter case, this method will escape argument keys and values according to the URI escaping rule.</p>
<p>Multi-value arguments are also supported:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">set_uri_args</span><span class="p">({</span> <span class="n">a</span> <span class="o">=</span> <span class="mi">3</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="p">{</span><span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">}</span> <span class="p">})</span>
</code></pre></div></div>
<p>which will result in a query string like <code class="language-plaintext highlighter-rouge">a=3&amp;b=5&amp;b=6</code>.</p>
<p>This interface was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc13</code> release.</p>
<p>See also <a href="#ngxreqset_uri">ngx.req.set_uri</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqget_uri_args">ngx.req.get_uri_args</h2>
<p><strong>syntax:</strong> <em>args = ngx.req.get_uri_args(max_args?)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua, log_by_lua**</p>
<p>Returns a Lua table holding all the current request URL query arguments.</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="p">=</span> <span class="n">/test</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">args</span> <span class="p">=</span> <span class="s">ngx.req.get_uri_args()</span>
<span class="s">for</span> <span class="s">key,</span> <span class="s">val</span> <span class="s">in</span> <span class="s">pairs(args)</span> <span class="s">do</span>
<span class="s">if</span> <span class="s">type(val)</span> <span class="p">==</span> <span class="s">"table"</span> <span class="s">then</span>
<span class="s">ngx.say(key,</span> <span class="s">":</span> <span class="s">",</span> <span class="s">table.concat(val,</span> <span class="s">",</span> <span class="s">"))</span>
<span class="s">else</span>
<span class="s">ngx.say(key,</span> <span class="s">":</span> <span class="s">",</span> <span class="s">val)</span>
<span class="s">end</span>
<span class="s">end</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Then <code class="language-plaintext highlighter-rouge">GET /test?foo=bar&amp;bar=baz&amp;bar=blah</code> will yield the response body</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
foo: bar
bar: baz, blah
</code></pre></div></div>
<p>Multiple occurrences of an argument key will result in a table value holding all the values for that key in order.</p>
<p>Keys and values are unescaped according to URI escaping rules. In the settings above, <code class="language-plaintext highlighter-rouge">GET /test?a%20b=1%61+2</code> will yield:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
a b: 1a 2
</code></pre></div></div>
<p>Arguments without the <code class="language-plaintext highlighter-rouge">=&lt;value&gt;</code> parts are treated as boolean arguments. <code class="language-plaintext highlighter-rouge">GET /test?foo&amp;bar</code> will yield:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
foo: <span class="nb">true
</span>bar: <span class="nb">true</span>
</code></pre></div></div>
<p>That is, they will take Lua boolean values <code class="language-plaintext highlighter-rouge">true</code>. However, they are different from arguments taking empty string values. <code class="language-plaintext highlighter-rouge">GET /test?foo=&amp;bar=</code> will give something like</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
foo:
bar:
</code></pre></div></div>
<p>Empty key arguments are discarded. <code class="language-plaintext highlighter-rouge">GET /test?=hello&amp;=world</code> will yield an empty output for instance.</p>
<p>Updating query arguments via the nginx variable <code class="language-plaintext highlighter-rouge">$args</code> (or <code class="language-plaintext highlighter-rouge">ngx.var.args</code> in Lua) at runtime is also supported:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">var</span><span class="p">.</span><span class="n">args</span> <span class="o">=</span> <span class="s2">"a=3&amp;b=42"</span>
<span class="kd">local</span> <span class="n">args</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">get_uri_args</span><span class="p">()</span>
</code></pre></div></div>
<p>Here the <code class="language-plaintext highlighter-rouge">args</code> table will always look like</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="p">{</span><span class="n">a</span> <span class="o">=</span> <span class="mi">3</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">42</span><span class="p">}</span>
</code></pre></div></div>
<p>regardless of the actual request query string.</p>
<p>Note that a maximum of 100 request arguments are parsed by default (including those with the same name) and that additional request arguments are silently discarded to guard against potential denial of service attacks.</p>
<p>However, the optional <code class="language-plaintext highlighter-rouge">max_args</code> function argument can be used to override this limit:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">args</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">get_uri_args</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
</code></pre></div></div>
<p>This argument can be set to zero to remove the limit and to process all request arguments received:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">args</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">get_uri_args</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
</code></pre></div></div>
<p>Removing the <code class="language-plaintext highlighter-rouge">max_args</code> cap is strongly discouraged.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqget_post_args">ngx.req.get_post_args</h2>
<p><strong>syntax:</strong> <em>args, err = ngx.req.get_post_args(max_args?)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua*, body_filter_by_lua, log_by_lua**</p>
<p>Returns a Lua table holding all the current request POST query arguments (of the MIME type <code class="language-plaintext highlighter-rouge">application/x-www-form-urlencoded</code>). Call <a href="#ngxreqread_body">ngx.req.read_body</a> to read the request body first or turn on the <a href="#lua_need_request_body">lua_need_request_body</a> directive to avoid errors.</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="p">=</span> <span class="n">/test</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">ngx.req.read_body()</span>
<span class="s">local</span> <span class="s">args,</span> <span class="s">err</span> <span class="p">=</span> <span class="s">ngx.req.get_post_args()</span>
<span class="s">if</span> <span class="s">not</span> <span class="s">args</span> <span class="s">then</span>
<span class="s">ngx.say("failed</span> <span class="s">to</span> <span class="s">get</span> <span class="s">post</span> <span class="s">args:</span> <span class="s">",</span> <span class="s">err)</span>
<span class="s">return</span>
<span class="s">end</span>
<span class="s">for</span> <span class="s">key,</span> <span class="s">val</span> <span class="s">in</span> <span class="s">pairs(args)</span> <span class="s">do</span>
<span class="s">if</span> <span class="s">type(val)</span> <span class="p">==</span> <span class="s">"table"</span> <span class="s">then</span>
<span class="s">ngx.say(key,</span> <span class="s">":</span> <span class="s">",</span> <span class="s">table.concat(val,</span> <span class="s">",</span> <span class="s">"))</span>
<span class="s">else</span>
<span class="s">ngx.say(key,</span> <span class="s">":</span> <span class="s">",</span> <span class="s">val)</span>
<span class="s">end</span>
<span class="s">end</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Then</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="c"># Post request with the body 'foo=bar&amp;bar=baz&amp;bar=blah'</span>
<span class="nv">$ </span>curl <span class="nt">--data</span> <span class="s1">'foo=bar&amp;bar=baz&amp;bar=blah'</span> localhost/test
</code></pre></div></div>
<p>will yield the response body like</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
foo: bar
bar: baz, blah
</code></pre></div></div>
<p>Multiple occurrences of an argument key will result in a table value holding all of the values for that key in order.</p>
<p>Keys and values will be unescaped according to URI escaping rules.</p>
<p>With the settings above,</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="c"># POST request with body 'a%20b=1%61+2'</span>
<span class="nv">$ </span>curl <span class="nt">-d</span> <span class="s1">'a%20b=1%61+2'</span> localhost/test
</code></pre></div></div>
<p>will yield:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
a b: 1a 2
</code></pre></div></div>
<p>Arguments without the <code class="language-plaintext highlighter-rouge">=&lt;value&gt;</code> parts are treated as boolean arguments. <code class="language-plaintext highlighter-rouge">POST /test</code> with the request body <code class="language-plaintext highlighter-rouge">foo&amp;bar</code> will yield:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
foo: <span class="nb">true
</span>bar: <span class="nb">true</span>
</code></pre></div></div>
<p>That is, they will take Lua boolean values <code class="language-plaintext highlighter-rouge">true</code>. However, they are different from arguments taking empty string values. <code class="language-plaintext highlighter-rouge">POST /test</code> with request body <code class="language-plaintext highlighter-rouge">foo=&amp;bar=</code> will return something like</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
foo:
bar:
</code></pre></div></div>
<p>Empty key arguments are discarded. <code class="language-plaintext highlighter-rouge">POST /test</code> with body <code class="language-plaintext highlighter-rouge">=hello&amp;=world</code> will yield empty outputs for instance.</p>
<p>Note that a maximum of 100 request arguments are parsed by default (including those with the same name) and that additional request arguments are silently discarded to guard against potential denial of service attacks.</p>
<p>However, the optional <code class="language-plaintext highlighter-rouge">max_args</code> function argument can be used to override this limit:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">args</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">get_post_args</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
</code></pre></div></div>
<p>This argument can be set to zero to remove the limit and to process all request arguments received:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">args</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">get_post_args</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
</code></pre></div></div>
<p>Removing the <code class="language-plaintext highlighter-rouge">max_args</code> cap is strongly discouraged.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqget_headers">ngx.req.get_headers</h2>
<p><strong>syntax:</strong> <em>headers = ngx.req.get_headers(max_headers?, raw?)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua, log_by_lua**</p>
<p>Returns a Lua table holding all the current request headers.</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">h</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">get_headers</span><span class="p">()</span>
<span class="k">for</span> <span class="n">k</span><span class="p">,</span> <span class="n">v</span> <span class="k">in</span> <span class="nb">pairs</span><span class="p">(</span><span class="n">h</span><span class="p">)</span> <span class="k">do</span>
<span class="o">...</span>
<span class="k">end</span>
</code></pre></div></div>
<p>To read an individual header:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"Host: "</span><span class="p">,</span> <span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">get_headers</span><span class="p">()[</span><span class="s2">"Host"</span><span class="p">])</span>
</code></pre></div></div>
<p>Note that the <a href="#ngxvarvariable">ngx.var.HEADER</a> API call, which uses core <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#var_http_">$http_HEADER</a> variables, may be more preferable for reading individual request headers.</p>
<p>For multiple instances of request headers such as:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
Foo: foo
Foo: bar
Foo: baz
</code></pre></div></div>
<p>the value of <code class="language-plaintext highlighter-rouge">ngx.req.get_headers()["Foo"]</code> will be a Lua (array) table such as:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="p">{</span><span class="s2">"foo"</span><span class="p">,</span> <span class="s2">"bar"</span><span class="p">,</span> <span class="s2">"baz"</span><span class="p">}</span>
</code></pre></div></div>
<p>Note that a maximum of 100 request headers are parsed by default (including those with the same name) and that additional request headers are silently discarded to guard against potential denial of service attacks.</p>
<p>However, the optional <code class="language-plaintext highlighter-rouge">max_headers</code> function argument can be used to override this limit:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">headers</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">get_headers</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
</code></pre></div></div>
<p>This argument can be set to zero to remove the limit and to process all request headers received:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">headers</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">get_headers</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
</code></pre></div></div>
<p>Removing the <code class="language-plaintext highlighter-rouge">max_headers</code> cap is strongly discouraged.</p>
<p>Since the <code class="language-plaintext highlighter-rouge">0.6.9</code> release, all the header names in the Lua table returned are converted to the pure lower-case form by default, unless the <code class="language-plaintext highlighter-rouge">raw</code> argument is set to <code class="language-plaintext highlighter-rouge">true</code> (default to <code class="language-plaintext highlighter-rouge">false</code>).</p>
<p>Also, by default, an <code class="language-plaintext highlighter-rouge">__index</code> metamethod is added to the resulting Lua table and will normalize the keys to a pure lowercase form with all underscores converted to dashes in case of a lookup miss. For example, if a request header <code class="language-plaintext highlighter-rouge">My-Foo-Header</code> is present, then the following invocations will all pick up the value of this header correctly:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="n">headers</span><span class="p">.</span><span class="n">my_foo_header</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="n">headers</span><span class="p">[</span><span class="s2">"My-Foo-Header"</span><span class="p">])</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="n">headers</span><span class="p">[</span><span class="s2">"my-foo-header"</span><span class="p">])</span>
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">__index</code> metamethod will not be added when the <code class="language-plaintext highlighter-rouge">raw</code> argument is set to <code class="language-plaintext highlighter-rouge">true</code>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqset_header">ngx.req.set_header</h2>
<p><strong>syntax:</strong> <em>ngx.req.set_header(header_name, header_value)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua*</p>
<p>Set the current requests request header named <code class="language-plaintext highlighter-rouge">header_name</code> to value <code class="language-plaintext highlighter-rouge">header_value</code>, overriding any existing ones.</p>
<p>By default, all the subrequests subsequently initiated by <a href="#ngxlocationcapture">ngx.location.capture</a> and <a href="#ngxlocationcapture_multi">ngx.location.capture_multi</a> will inherit the new header.</p>
<p>Here is an example of setting the <code class="language-plaintext highlighter-rouge">Content-Type</code> header:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">set_header</span><span class="p">(</span><span class="s2">"Content-Type"</span><span class="p">,</span> <span class="s2">"text/css"</span><span class="p">)</span>
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">header_value</code> can take an array list of values,
for example,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">set_header</span><span class="p">(</span><span class="s2">"Foo"</span><span class="p">,</span> <span class="p">{</span><span class="s2">"a"</span><span class="p">,</span> <span class="s2">"abc"</span><span class="p">})</span>
</code></pre></div></div>
<p>will produce two new request headers:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
Foo: a
Foo: abc
</code></pre></div></div>
<p>and old <code class="language-plaintext highlighter-rouge">Foo</code> headers will be overridden if there is any.</p>
<p>When the <code class="language-plaintext highlighter-rouge">header_value</code> argument is <code class="language-plaintext highlighter-rouge">nil</code>, the request header will be removed. So</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">set_header</span><span class="p">(</span><span class="s2">"X-Foo"</span><span class="p">,</span> <span class="kc">nil</span><span class="p">)</span>
</code></pre></div></div>
<p>is equivalent to</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">clear_header</span><span class="p">(</span><span class="s2">"X-Foo"</span><span class="p">)</span>
</code></pre></div></div>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqclear_header">ngx.req.clear_header</h2>
<p><strong>syntax:</strong> <em>ngx.req.clear_header(header_name)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua**</p>
<p>Clears the current requests request header named <code class="language-plaintext highlighter-rouge">header_name</code>. None of the current requests existing subrequests will be affected but subsequently initiated subrequests will inherit the change by default.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqread_body">ngx.req.read_body</h2>
<p><strong>syntax:</strong> <em>ngx.req.read_body()</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua*, content_by_lua**</p>
<p>Reads the client request body synchronously without blocking the Nginx event loop.</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">read_body</span><span class="p">()</span>
<span class="kd">local</span> <span class="n">args</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">get_post_args</span><span class="p">()</span>
</code></pre></div></div>
<p>If the request body is already read previously by turning on <a href="#lua_need_request_body">lua_need_request_body</a> or by using other modules, then this function does not run and returns immediately.</p>
<p>If the request body has already been explicitly discarded, either by the <a href="#ngxreqdiscard_body">ngx.req.discard_body</a> function or other modules, this function does not run and returns immediately.</p>
<p>In case of errors, such as connection errors while reading the data, this method will throw out a Lua exception <em>or</em> terminate the current request with a 500 status code immediately.</p>
<p>The request body data read using this function can be retrieved later via <a href="#ngxreqget_body_data">ngx.req.get_body_data</a> or, alternatively, the temporary file name for the body data cached to disk using <a href="#ngxreqget_body_file">ngx.req.get_body_file</a>. This depends on</p>
<ol>
<li>whether the current request body is already larger than the <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size">client_body_buffer_size</a>,</li>
<li>and whether <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_in_file_only">client_body_in_file_only</a> has been switched on.</li>
</ol>
<p>In cases where current request may have a request body and the request body data is not required, The <a href="#ngxreqdiscard_body">ngx.req.discard_body</a> function must be used to explicitly discard the request body to avoid breaking things under HTTP 1.1 keepalive or HTTP 1.1 pipelining.</p>
<p>This function was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc17</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqdiscard_body">ngx.req.discard_body</h2>
<p><strong>syntax:</strong> <em>ngx.req.discard_body()</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua*, content_by_lua**</p>
<p>Explicitly discard the request body, i.e., read the data on the connection and throw it away immediately. Please note that ignoring request body is not the right way to discard it, and that this function must be called to avoid breaking things under HTTP 1.1 keepalive or HTTP 1.1 pipelining.</p>
<p>This function is an asynchronous call and returns immediately.</p>
<p>If the request body has already been read, this function does nothing and returns immediately.</p>
<p>This function was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc17</code> release.</p>
<p>See also <a href="#ngxreqread_body">ngx.req.read_body</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqget_body_data">ngx.req.get_body_data</h2>
<p><strong>syntax:</strong> <em>data = ngx.req.get_body_data()</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua*, content_by_lua**</p>
<p>Retrieves in-memory request body data. It returns a Lua string rather than a Lua table holding all the parsed query arguments. Use the <a href="#ngxreqget_post_args">ngx.req.get_post_args</a> function instead if a Lua table is required.</p>
<p>This function returns <code class="language-plaintext highlighter-rouge">nil</code> if</p>
<ol>
<li>the request body has not been read,</li>
<li>the request body has been read into disk temporary files,</li>
<li>or the request body has zero size.</li>
</ol>
<p>If the request body has not been read yet, call <a href="#ngxreqread_body">ngx.req.read_body</a> first (or turned on <a href="#lua_need_request_body">lua_need_request_body</a> to force this module to read the request body. This is not recommended however).</p>
<p>If the request body has been read into disk files, try calling the <a href="#ngxreqget_body_file">ngx.req.get_body_file</a> function instead.</p>
<p>To force in-memory request bodies, try setting <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size">client_body_buffer_size</a> to the same size value in <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#client_max_body_size">client_max_body_size</a>.</p>
<p>Note that calling this function instead of using <code class="language-plaintext highlighter-rouge">ngx.var.request_body</code> or <code class="language-plaintext highlighter-rouge">ngx.var.echo_request_body</code> is more efficient because it can save one dynamic memory allocation and one data copy.</p>
<p>This function was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc17</code> release.</p>
<p>See also <a href="#ngxreqget_body_file">ngx.req.get_body_file</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqget_body_file">ngx.req.get_body_file</h2>
<p><strong>syntax:</strong> <em>file_name = ngx.req.get_body_file()</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua*, content_by_lua**</p>
<p>Retrieves the file name for the in-file request body data. Returns <code class="language-plaintext highlighter-rouge">nil</code> if the request body has not been read or has been read into memory.</p>
<p>The returned file is read only and is usually cleaned up by Nginxs memory pool. It should not be manually modified, renamed, or removed in Lua code.</p>
<p>If the request body has not been read yet, call <a href="#ngxreqread_body">ngx.req.read_body</a> first (or turned on <a href="#lua_need_request_body">lua_need_request_body</a> to force this module to read the request body. This is not recommended however).</p>
<p>If the request body has been read into memory, try calling the <a href="#ngxreqget_body_data">ngx.req.get_body_data</a> function instead.</p>
<p>To force in-file request bodies, try turning on <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_in_file_only">client_body_in_file_only</a>.</p>
<p>This function was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc17</code> release.</p>
<p>See also <a href="#ngxreqget_body_data">ngx.req.get_body_data</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqset_body_data">ngx.req.set_body_data</h2>
<p><strong>syntax:</strong> <em>ngx.req.set_body_data(data)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua*, content_by_lua**</p>
<p>Set the current requests request body using the in-memory data specified by the <code class="language-plaintext highlighter-rouge">data</code> argument.</p>
<p>If the current requests request body has not been read, then it will be properly discarded. When the current requests request body has been read into memory or buffered into a disk file, then the old request bodys memory will be freed or the disk file will be cleaned up immediately, respectively.</p>
<p>This function was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc18</code> release.</p>
<p>See also <a href="#ngxreqset_body_file">ngx.req.set_body_file</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqset_body_file">ngx.req.set_body_file</h2>
<p><strong>syntax:</strong> <em>ngx.req.set_body_file(file_name, auto_clean?)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua*, content_by_lua**</p>
<p>Set the current requests request body using the in-file data specified by the <code class="language-plaintext highlighter-rouge">file_name</code> argument.</p>
<p>If the optional <code class="language-plaintext highlighter-rouge">auto_clean</code> argument is given a <code class="language-plaintext highlighter-rouge">true</code> value, then this file will be removed at request completion or the next time this function or <a href="#ngxreqset_body_data">ngx.req.set_body_data</a> are called in the same request. The <code class="language-plaintext highlighter-rouge">auto_clean</code> is default to <code class="language-plaintext highlighter-rouge">false</code>.</p>
<p>Please ensure that the file specified by the <code class="language-plaintext highlighter-rouge">file_name</code> argument exists and is readable by an Nginx worker process by setting its permission properly to avoid Lua exception errors.</p>
<p>If the current requests request body has not been read, then it will be properly discarded. When the current requests request body has been read into memory or buffered into a disk file, then the old request bodys memory will be freed or the disk file will be cleaned up immediately, respectively.</p>
<p>This function was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc18</code> release.</p>
<p>See also <a href="#ngxreqset_body_data">ngx.req.set_body_data</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqinit_body">ngx.req.init_body</h2>
<p><strong>syntax:</strong> <em>ngx.req.init_body(buffer_size?)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua**</p>
<p>Creates a new blank request body for the current request and inializes the buffer for later request body data writing via the <a href="#ngxreqappend_body">ngx.req.append_body</a> and <a href="#ngxreqfinish_body">ngx.req.finish_body</a> APIs.</p>
<p>If the <code class="language-plaintext highlighter-rouge">buffer_size</code> argument is specified, then its value will be used for the size of the memory buffer for body writing with <a href="#ngxreqappend_body">ngx.req.append_body</a>. If the argument is omitted, then the value specified by the standard <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_buffer_size">client_body_buffer_size</a> directive will be used instead.</p>
<p>When the data can no longer be hold in the memory buffer for the request body, then the data will be flushed onto a temporary file just like the standard request body reader in the Nginx core.</p>
<p>It is important to always call the <a href="#ngxreqfinish_body">ngx.req.finish_body</a> after all the data has been appended onto the current request body. Also, when this function is used together with <a href="#ngxreqsocket">ngx.req.socket</a>, it is required to call <a href="#ngxreqsocket">ngx.req.socket</a> <em>before</em> this function, or you will get the “request body already exists” error message.</p>
<p>The usage of this function is often like this:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">init_body</span><span class="p">(</span><span class="mi">128</span> <span class="o">*</span> <span class="mi">1024</span><span class="p">)</span> <span class="c1">-- buffer is 128KB</span>
<span class="k">for</span> <span class="n">chunk</span> <span class="k">in</span> <span class="n">next_data_chunk</span><span class="p">()</span> <span class="k">do</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">append_body</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span> <span class="c1">-- each chunk can be 4KB</span>
<span class="k">end</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">req</span><span class="p">.</span><span class="n">finish_body</span><span class="p">()</span>
</code></pre></div></div>
<p>This function can be used with <a href="#ngxreqappend_body">ngx.req.append_body</a>, <a href="#ngxreqfinish_body">ngx.req.finish_body</a>, and <a href="#ngxreqsocket">ngx.req.socket</a> to implement efficient input filters in pure Lua (in the context of <a href="#rewrite_by_lua">rewrite_by_lua</a>* or <a href="#access_by_lua">access_by_lua</a>*), which can be used with other Nginx content handler or upstream modules like <a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html">ngx_http_proxy_module</a> and <a href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html">ngx_http_fastcgi_module</a>.</p>
<p>This function was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.11</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqappend_body">ngx.req.append_body</h2>
<p><strong>syntax:</strong> <em>ngx.req.append_body(data_chunk)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua**</p>
<p>Append new data chunk specified by the <code class="language-plaintext highlighter-rouge">data_chunk</code> argument onto the existing request body created by the <a href="#ngxreqinit_body">ngx.req.init_body</a> call.</p>
<p>When the data can no longer be hold in the memory buffer for the request body, then the data will be flushed onto a temporary file just like the standard request body reader in the Nginx core.</p>
<p>It is important to always call the <a href="#ngxreqfinish_body">ngx.req.finish_body</a> after all the data has been appended onto the current request body.</p>
<p>This function can be used with <a href="#ngxreqinit_body">ngx.req.init_body</a>, <a href="#ngxreqfinish_body">ngx.req.finish_body</a>, and <a href="#ngxreqsocket">ngx.req.socket</a> to implement efficient input filters in pure Lua (in the context of <a href="#rewrite_by_lua">rewrite_by_lua</a>* or <a href="#access_by_lua">access_by_lua</a>*), which can be used with other Nginx content handler or upstream modules like <a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html">ngx_http_proxy_module</a> and <a href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html">ngx_http_fastcgi_module</a>.</p>
<p>This function was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.11</code> release.</p>
<p>See also <a href="#ngxreqinit_body">ngx.req.init_body</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqfinish_body">ngx.req.finish_body</h2>
<p><strong>syntax:</strong> <em>ngx.req.finish_body()</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua**</p>
<p>Completes the construction process of the new request body created by the <a href="#ngxreqinit_body">ngx.req.init_body</a> and <a href="#ngxreqappend_body">ngx.req.append_body</a> calls.</p>
<p>This function can be used with <a href="#ngxreqinit_body">ngx.req.init_body</a>, <a href="#ngxreqappend_body">ngx.req.append_body</a>, and <a href="#ngxreqsocket">ngx.req.socket</a> to implement efficient input filters in pure Lua (in the context of <a href="#rewrite_by_lua">rewrite_by_lua</a>* or <a href="#access_by_lua">access_by_lua</a>*), which can be used with other Nginx content handler or upstream modules like <a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html">ngx_http_proxy_module</a> and <a href="http://nginx.org/en/docs/http/ngx_http_fastcgi_module.html">ngx_http_fastcgi_module</a>.</p>
<p>This function was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.11</code> release.</p>
<p>See also <a href="#ngxreqinit_body">ngx.req.init_body</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxreqsocket">ngx.req.socket</h2>
<p><strong>syntax:</strong> <em>tcpsock, err = ngx.req.socket()</em></p>
<p><strong>syntax:</strong> <em>tcpsock, err = ngx.req.socket(raw)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua*, content_by_lua**</p>
<p>Returns a read-only cosocket object that wraps the downstream connection. Only <a href="#tcpsockreceive">receive</a> and <a href="#tcpsockreceiveuntil">receiveuntil</a> methods are supported on this object.</p>
<p>In case of error, <code class="language-plaintext highlighter-rouge">nil</code> will be returned as well as a string describing the error.</p>
<p>The socket object returned by this method is usually used to read the current requests body in a streaming fashion. Do not turn on the <a href="#lua_need_request_body">lua_need_request_body</a> directive, and do not mix this call with <a href="#ngxreqread_body">ngx.req.read_body</a> and <a href="#ngxreqdiscard_body">ngx.req.discard_body</a>.</p>
<p>If any request body data has been pre-read into the Nginx core request header buffer, the resulting cosocket object will take care of this to avoid potential data loss resulting from such pre-reading.
Chunked request bodies are not yet supported in this API.</p>
<p>Since the <code class="language-plaintext highlighter-rouge">v0.9.0</code> release, this function accepts an optional boolean <code class="language-plaintext highlighter-rouge">raw</code> argument. When this argument is <code class="language-plaintext highlighter-rouge">true</code>, this function returns a full-duplex cosocket object wrapping around the raw downstream connection socket, upon which you can call the <a href="#tcpsockreceive">receive</a>, <a href="#tcpsockreceiveuntil">receiveuntil</a>, and <a href="#tcpsocksend">send</a> methods.</p>
<p>When the <code class="language-plaintext highlighter-rouge">raw</code> argument is <code class="language-plaintext highlighter-rouge">true</code>, it is required that no pending data from any previous <a href="#ngxsay">ngx.say</a>, <a href="#ngxprint">ngx.print</a>, or <a href="#ngxsend_headers">ngx.send_headers</a> calls exists. So if you have these downstream output calls previously, you should call <a href="#ngxflush">ngx.flush(true)</a> before calling <code class="language-plaintext highlighter-rouge">ngx.req.socket(true)</code> to ensure that there is no pending output data. If the request body has not been read yet, then this “raw socket” can also be used to read the request body.</p>
<p>You can use the “raw request socket” returned by <code class="language-plaintext highlighter-rouge">ngx.req.socket(true)</code> to implement fancy protocols like <a href="http://en.wikipedia.org/wiki/WebSocket">WebSocket</a>, or just emit your own raw HTTP response header or body data. You can refer to the <a href="https://github.com/openresty/lua-resty-websocket">lua-resty-websocket library</a> for a real world example.</p>
<p>This function was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc1</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxexec">ngx.exec</h2>
<p><strong>syntax:</strong> <em>ngx.exec(uri, args?)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua*, content_by_lua**</p>
<p>Does an internal redirect to <code class="language-plaintext highlighter-rouge">uri</code> with <code class="language-plaintext highlighter-rouge">args</code> and is similar to the <a href="http://github.com/openresty/echo-nginx-module#echo_exec">echo_exec</a> directive of the <a href="http://github.com/openresty/echo-nginx-module">echo-nginx-module</a>.</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">exec</span><span class="p">(</span><span class="s1">'/some-location'</span><span class="p">);</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">exec</span><span class="p">(</span><span class="s1">'/some-location'</span><span class="p">,</span> <span class="s1">'a=3&amp;b=5&amp;c=6'</span><span class="p">);</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">exec</span><span class="p">(</span><span class="s1">'/some-location?a=3&amp;b=5'</span><span class="p">,</span> <span class="s1">'c=6'</span><span class="p">);</span>
</code></pre></div></div>
<p>The optional second <code class="language-plaintext highlighter-rouge">args</code> can be used to specify extra URI query arguments, for example:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">exec</span><span class="p">(</span><span class="s2">"/foo"</span><span class="p">,</span> <span class="s2">"a=3&amp;b=hello%20world"</span><span class="p">)</span>
</code></pre></div></div>
<p>Alternatively, a Lua table can be passed for the <code class="language-plaintext highlighter-rouge">args</code> argument for ngx_lua to carry out URI escaping and string concatenation.</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">exec</span><span class="p">(</span><span class="s2">"/foo"</span><span class="p">,</span> <span class="p">{</span> <span class="n">a</span> <span class="o">=</span> <span class="mi">3</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="s2">"hello world"</span> <span class="p">})</span>
</code></pre></div></div>
<p>The result is exactly the same as the previous example.</p>
<p>The format for the Lua table passed as the <code class="language-plaintext highlighter-rouge">args</code> argument is identical to the format used in the <a href="#ngxencode_args">ngx.encode_args</a> method.</p>
<p>Named locations are also supported but the second <code class="language-plaintext highlighter-rouge">args</code> argument will be ignored if present and the querystring for the new target is inherited from the referring location (if any).</p>
<p><code class="language-plaintext highlighter-rouge">GET /foo/file.php?a=hello</code> will return “hello” and not “goodbye” in the example below</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/foo</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">ngx.exec("@bar",</span> <span class="s">"a=goodbye")</span><span class="p">;</span>
<span class="kn">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">location</span> <span class="s">@bar</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">args</span> <span class="p">=</span> <span class="s">ngx.req.get_uri_args()</span>
<span class="s">for</span> <span class="s">key,</span> <span class="s">val</span> <span class="s">in</span> <span class="s">pairs(args)</span> <span class="s">do</span>
<span class="s">if</span> <span class="s">key</span> <span class="p">==</span> <span class="s">"a"</span> <span class="s">then</span>
<span class="s">ngx.say(val)</span>
<span class="s">end</span>
<span class="s">end</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Note that the <code class="language-plaintext highlighter-rouge">ngx.exec</code> method is different from <a href="#ngxredirect">ngx.redirect</a> in that
it is purely an internal redirect and that no new external HTTP traffic is involved.</p>
<p>Also note that this method call terminates the processing of the current request and that it <em>must</em> be called before <a href="#ngxsend_headers">ngx.send_headers</a> or explicit response body
outputs by either <a href="#ngxprint">ngx.print</a> or <a href="#ngxsay">ngx.say</a>.</p>
<p>It is recommended that a coding style that combines this method call with the <code class="language-plaintext highlighter-rouge">return</code> statement, i.e., <code class="language-plaintext highlighter-rouge">return ngx.exec(...)</code> be adopted when this method call is used in contexts other than <a href="#header_filter_by_lua">header_filter_by_lua</a> to reinforce the fact that the request processing is being terminated.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxredirect">ngx.redirect</h2>
<p><strong>syntax:</strong> <em>ngx.redirect(uri, status?)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua*, content_by_lua**</p>
<p>Issue an <code class="language-plaintext highlighter-rouge">HTTP 301</code> or <code class="language-plaintext highlighter-rouge">302</code> redirection to <code class="language-plaintext highlighter-rouge">uri</code>.</p>
<p>The optional <code class="language-plaintext highlighter-rouge">status</code> parameter specifies whether
<code class="language-plaintext highlighter-rouge">301</code> or <code class="language-plaintext highlighter-rouge">302</code> to be used. It is <code class="language-plaintext highlighter-rouge">302</code> (<code class="language-plaintext highlighter-rouge">ngx.HTTP_MOVED_TEMPORARILY</code>) by default.</p>
<p>Here is an example assuming the current server name is <code class="language-plaintext highlighter-rouge">localhost</code> and that it is listening on port 1984:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">return</span> <span class="n">ngx</span><span class="p">.</span><span class="n">redirect</span><span class="p">(</span><span class="s2">"/foo"</span><span class="p">)</span>
</code></pre></div></div>
<p>which is equivalent to</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">return</span> <span class="n">ngx</span><span class="p">.</span><span class="n">redirect</span><span class="p">(</span><span class="s2">"/foo"</span><span class="p">,</span> <span class="n">ngx</span><span class="p">.</span><span class="n">HTTP_MOVED_TEMPORARILY</span><span class="p">)</span>
</code></pre></div></div>
<p>Redirecting arbitrary external URLs is also supported, for example:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">return</span> <span class="n">ngx</span><span class="p">.</span><span class="n">redirect</span><span class="p">(</span><span class="s2">"http://www.google.com"</span><span class="p">)</span>
</code></pre></div></div>
<p>We can also use the numerical code directly as the second <code class="language-plaintext highlighter-rouge">status</code> argument:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">return</span> <span class="n">ngx</span><span class="p">.</span><span class="n">redirect</span><span class="p">(</span><span class="s2">"/foo"</span><span class="p">,</span> <span class="mi">301</span><span class="p">)</span>
</code></pre></div></div>
<p>This method is similar to the <a href="http://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite">rewrite</a> directive with the <code class="language-plaintext highlighter-rouge">redirect</code> modifier in the standard
<a href="http://nginx.org/en/docs/http/ngx_http_rewrite_module.html">ngx_http_rewrite_module</a>, for example, this <code class="language-plaintext highlighter-rouge">nginx.conf</code> snippet</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">rewrite</span> <span class="s">^</span> <span class="n">/foo?</span> <span class="s">redirect</span><span class="p">;</span> <span class="c1"># nginx config</span>
</code></pre></div></div>
<p>is equivalent to the following Lua code</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">return</span> <span class="n">ngx</span><span class="p">.</span><span class="n">redirect</span><span class="p">(</span><span class="s1">'/foo'</span><span class="p">);</span> <span class="c1">-- Lua code</span>
</code></pre></div></div>
<p>while</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">rewrite</span> <span class="s">^</span> <span class="n">/foo?</span> <span class="s">permanent</span><span class="p">;</span> <span class="c1"># nginx config</span>
</code></pre></div></div>
<p>is equivalent to</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">return</span> <span class="n">ngx</span><span class="p">.</span><span class="n">redirect</span><span class="p">(</span><span class="s1">'/foo'</span><span class="p">,</span> <span class="n">ngx</span><span class="p">.</span><span class="n">HTTP_MOVED_PERMANENTLY</span><span class="p">)</span> <span class="c1">-- Lua code</span>
</code></pre></div></div>
<p>URI arguments can be specified as well, for example:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">return</span> <span class="n">ngx</span><span class="p">.</span><span class="n">redirect</span><span class="p">(</span><span class="s1">'/foo?a=3&amp;b=4'</span><span class="p">)</span>
</code></pre></div></div>
<p>Note that this method call terminates the processing of the current request and that it <em>must</em> be called before <a href="#ngxsend_headers">ngx.send_headers</a> or explicit response body
outputs by either <a href="#ngxprint">ngx.print</a> or <a href="#ngxsay">ngx.say</a>.</p>
<p>It is recommended that a coding style that combines this method call with the <code class="language-plaintext highlighter-rouge">return</code> statement, i.e., <code class="language-plaintext highlighter-rouge">return ngx.redirect(...)</code> be adopted when this method call is used in contexts other than <a href="#header_filter_by_lua">header_filter_by_lua</a> to reinforce the fact that the request processing is being terminated.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxsend_headers">ngx.send_headers</h2>
<p><strong>syntax:</strong> <em>ok, err = ngx.send_headers()</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua*, content_by_lua**</p>
<p>Explicitly send out the response headers.</p>
<p>Since <code class="language-plaintext highlighter-rouge">v0.8.3</code> this function returns <code class="language-plaintext highlighter-rouge">1</code> on success, or returns <code class="language-plaintext highlighter-rouge">nil</code> and a string describing the error otherwise.</p>
<p>Note that there is normally no need to manually send out response headers as ngx_lua will automatically send headers out
before content is output with <a href="#ngxsay">ngx.say</a> or <a href="#ngxprint">ngx.print</a> or when <a href="#content_by_lua">content_by_lua</a> exits normally.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxheaders_sent">ngx.headers_sent</h2>
<p><strong>syntax:</strong> <em>value = ngx.headers_sent</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua**</p>
<p>Returns <code class="language-plaintext highlighter-rouge">true</code> if the response headers have been sent (by ngx_lua), and <code class="language-plaintext highlighter-rouge">false</code> otherwise.</p>
<p>This API was first introduced in ngx_lua v0.3.1rc6.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxprint">ngx.print</h2>
<p><strong>syntax:</strong> <em>ok, err = ngx.print(…)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua*, content_by_lua**</p>
<p>Emits arguments concatenated to the HTTP client (as response body). If response headers have not been sent, this function will send headers out first and then output body data.</p>
<p>Since <code class="language-plaintext highlighter-rouge">v0.8.3</code> this function returns <code class="language-plaintext highlighter-rouge">1</code> on success, or returns <code class="language-plaintext highlighter-rouge">nil</code> and a string describing the error otherwise.</p>
<p>Lua <code class="language-plaintext highlighter-rouge">nil</code> values will output <code class="language-plaintext highlighter-rouge">"nil"</code> strings and Lua boolean values will output <code class="language-plaintext highlighter-rouge">"true"</code> and <code class="language-plaintext highlighter-rouge">"false"</code> literal strings respectively.</p>
<p>Nested arrays of strings are permitted and the elements in the arrays will be sent one by one:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">table</span> <span class="o">=</span> <span class="p">{</span>
<span class="s2">"hello, "</span><span class="p">,</span>
<span class="p">{</span><span class="s2">"world: "</span><span class="p">,</span> <span class="kc">true</span><span class="p">,</span> <span class="s2">" or "</span><span class="p">,</span> <span class="kc">false</span><span class="p">,</span>
<span class="p">{</span><span class="s2">": "</span><span class="p">,</span> <span class="kc">nil</span><span class="p">}}</span>
<span class="p">}</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">print</span><span class="p">(</span><span class="n">table</span><span class="p">)</span>
</code></pre></div></div>
<p>will yield the output</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
hello, world: <span class="nb">true </span>or <span class="nb">false</span>: nil
</code></pre></div></div>
<p>Non-array table arguments will cause a Lua exception to be thrown.</p>
<p>The <code class="language-plaintext highlighter-rouge">ngx.null</code> constant will yield the <code class="language-plaintext highlighter-rouge">"null"</code> string output.</p>
<p>This is an asynchronous call and will return immediately without waiting for all the data to be written into the system send buffer. To run in synchronous mode, call <code class="language-plaintext highlighter-rouge">ngx.flush(true)</code> after calling <code class="language-plaintext highlighter-rouge">ngx.print</code>. This can be particularly useful for streaming output. See <a href="#ngxflush">ngx.flush</a> for more details.</p>
<p>Please note that both <code class="language-plaintext highlighter-rouge">ngx.print</code> and <a href="#ngxsay">ngx.say</a> will always invoke the whole Nginx output body filter chain, which is an expensive operation. So be careful when calling either of these two in a tight loop; buffer the data yourself in Lua and save the calls.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxsay">ngx.say</h2>
<p><strong>syntax:</strong> <em>ok, err = ngx.say(…)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua*, content_by_lua**</p>
<p>Just as <a href="#ngxprint">ngx.print</a> but also emit a trailing newline.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxlog">ngx.log</h2>
<p><strong>syntax:</strong> <em>ngx.log(log_level, …)</em></p>
<p><strong>context:</strong> <em>init_by_lua</em>, init_worker_by_lua<em>, set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.**</p>
<p>Log arguments concatenated to error.log with the given logging level.</p>
<p>Lua <code class="language-plaintext highlighter-rouge">nil</code> arguments are accepted and result in literal <code class="language-plaintext highlighter-rouge">"nil"</code> string while Lua booleans result in literal <code class="language-plaintext highlighter-rouge">"true"</code> or <code class="language-plaintext highlighter-rouge">"false"</code> string outputs. And the <code class="language-plaintext highlighter-rouge">ngx.null</code> constant will yield the <code class="language-plaintext highlighter-rouge">"null"</code> string output.</p>
<p>The <code class="language-plaintext highlighter-rouge">log_level</code> argument can take constants like <code class="language-plaintext highlighter-rouge">ngx.ERR</code> and <code class="language-plaintext highlighter-rouge">ngx.WARN</code>. Check out <a href="#nginx-log-level-constants">Nginx log level constants</a> for details.</p>
<p>There is a hard coded <code class="language-plaintext highlighter-rouge">2048</code> byte limitation on error message lengths in the Nginx core. This limit includes trailing newlines and leading time stamps. If the message size exceeds this limit, Nginx will truncate the message text accordingly. This limit can be manually modified by editing the <code class="language-plaintext highlighter-rouge">NGX_MAX_ERROR_STR</code> macro definition in the <code class="language-plaintext highlighter-rouge">src/core/ngx_log.h</code> file in the Nginx source tree.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxflush">ngx.flush</h2>
<p><strong>syntax:</strong> <em>ok, err = ngx.flush(wait?)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua*, content_by_lua**</p>
<p>Flushes response output to the client.</p>
<p><code class="language-plaintext highlighter-rouge">ngx.flush</code> accepts an optional boolean <code class="language-plaintext highlighter-rouge">wait</code> argument (Default: <code class="language-plaintext highlighter-rouge">false</code>) first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc34</code> release. When called with the default argument, it issues an asynchronous call (Returns immediately without waiting for output data to be written into the system send buffer). Calling the function with the <code class="language-plaintext highlighter-rouge">wait</code> argument set to <code class="language-plaintext highlighter-rouge">true</code> switches to synchronous mode.</p>
<p>In synchronous mode, the function will not return until all output data has been written into the system send buffer or until the <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#send_timeout">send_timeout</a> setting has expired. Note that using the Lua coroutine mechanism means that this function does not block the Nginx event loop even in the synchronous mode.</p>
<p>When <code class="language-plaintext highlighter-rouge">ngx.flush(true)</code> is called immediately after <a href="#ngxprint">ngx.print</a> or <a href="#ngxsay">ngx.say</a>, it causes the latter functions to run in synchronous mode. This can be particularly useful for streaming output.</p>
<p>Note that <code class="language-plaintext highlighter-rouge">ngx.flush</code> is not functional when in the HTTP 1.0 output buffering mode. See <a href="#http-10-support">HTTP 1.0 support</a>.</p>
<p>Since <code class="language-plaintext highlighter-rouge">v0.8.3</code> this function returns <code class="language-plaintext highlighter-rouge">1</code> on success, or returns <code class="language-plaintext highlighter-rouge">nil</code> and a string describing the error otherwise.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxexit">ngx.exit</h2>
<p><strong>syntax:</strong> <em>ngx.exit(status)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua*, ngx.timer.**</p>
<p>When <code class="language-plaintext highlighter-rouge">status &gt;= 200</code> (i.e., <code class="language-plaintext highlighter-rouge">ngx.HTTP_OK</code> and above), it will interrupt the execution of the current request and return status code to nginx.</p>
<p>When <code class="language-plaintext highlighter-rouge">status == 0</code> (i.e., <code class="language-plaintext highlighter-rouge">ngx.OK</code>), it will only quit the current phase handler (or the content handler if the <a href="#content_by_lua">content_by_lua</a> directive is used) and continue to run later phases (if any) for the current request.</p>
<p>The <code class="language-plaintext highlighter-rouge">status</code> argument can be <code class="language-plaintext highlighter-rouge">ngx.OK</code>, <code class="language-plaintext highlighter-rouge">ngx.ERROR</code>, <code class="language-plaintext highlighter-rouge">ngx.HTTP_NOT_FOUND</code>,
<code class="language-plaintext highlighter-rouge">ngx.HTTP_MOVED_TEMPORARILY</code>, or other <a href="#http-status-constants">HTTP status constants</a>.</p>
<p>To return an error page with custom contents, use code snippets like this:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">status</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">HTTP_GONE</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"This is our own content"</span><span class="p">)</span>
<span class="c1">-- to cause quit the whole request rather than the current phase handler</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">exit</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">HTTP_OK</span><span class="p">)</span>
</code></pre></div></div>
<p>The effect in action:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="nv">$ </span>curl <span class="nt">-i</span> http://localhost/test
HTTP/1.1 410 Gone
Server: nginx/1.0.6
Date: Thu, 15 Sep 2011 00:51:48 GMT
Content-Type: text/plain
Transfer-Encoding: chunked
Connection: keep-alive
This is our own content
</code></pre></div></div>
<p>Number literals can be used directly as the argument, for instance,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">501</span><span class="p">)</span>
</code></pre></div></div>
<p>Note that while this method accepts all <a href="#http-status-constants">HTTP status constants</a> as input, it only accepts <code class="language-plaintext highlighter-rouge">NGX_OK</code> and <code class="language-plaintext highlighter-rouge">NGX_ERROR</code> of the <a href="#core-constants">core constants</a>.</p>
<p>Also note that this method call terminates the processing of the current request and that it is recommended that a coding style that combines this method call with the <code class="language-plaintext highlighter-rouge">return</code> statement, i.e., <code class="language-plaintext highlighter-rouge">return ngx.exit(...)</code> be used to reinforce the fact that the request processing is being terminated.</p>
<p>When being used in the context of <a href="#header_filter_by_lua">header_filter_by_lua</a>, <code class="language-plaintext highlighter-rouge">ngx.exit()</code> is an asynchronous operation and will return immediately. This behavior may change in future and it is recommended that users always use <code class="language-plaintext highlighter-rouge">return</code> in combination as suggested above.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxeof">ngx.eof</h2>
<p><strong>syntax:</strong> <em>ok, err = ngx.eof()</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua*, content_by_lua**</p>
<p>Explicitly specify the end of the response output stream. In the case of HTTP 1.1 chunked encoded output, it will just trigger the Nginx core to send out the “last chunk”.</p>
<p>When you disable the HTTP 1.1 keep-alive feature for your downstream connections, you can rely on descent HTTP clients to close the connection actively for you when you call this method. This trick can be used do back-ground jobs without letting the HTTP clients to wait on the connection, as in the following example:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="p">=</span> <span class="n">/async</span> <span class="p">{</span>
<span class="kn">keepalive_timeout</span> <span class="mi">0</span><span class="p">;</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">ngx.say("got</span> <span class="s">the</span> <span class="s">task!")</span>
<span class="s">ngx.eof()</span> <span class="s">--</span> <span class="s">a</span> <span class="s">descent</span> <span class="s">HTTP</span> <span class="s">client</span> <span class="s">will</span> <span class="s">close</span> <span class="s">the</span> <span class="s">connection</span> <span class="s">at</span> <span class="s">this</span> <span class="s">point</span>
<span class="s">--</span> <span class="s">access</span> <span class="s">MySQL,</span> <span class="s">PostgreSQL,</span> <span class="s">Redis,</span> <span class="s">Memcached,</span> <span class="s">and</span> <span class="s">etc</span> <span class="s">here...</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>But if you create subrequests to access other locations configured by Nginx upstream modules, then you should configure those upstream modules to ignore client connection abortions if they are not by default. For example, by default the standard <a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html">ngx_http_proxy_module</a> will terminate both the subrequest and the main request as soon as the client closes the connection, so it is important to turn on the <a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_ignore_client_abort">proxy_ignore_client_abort</a> directive in your location block configured by <a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html">ngx_http_proxy_module</a>:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">proxy_ignore_client_abort</span> <span class="no">on</span><span class="p">;</span>
</code></pre></div></div>
<p>A better way to do background jobs is to use the <a href="#ngxtimerat">ngx.timer.at</a> API.</p>
<p>Since <code class="language-plaintext highlighter-rouge">v0.8.3</code> this function returns <code class="language-plaintext highlighter-rouge">1</code> on success, or returns <code class="language-plaintext highlighter-rouge">nil</code> and a string describing the error otherwise.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxsleep">ngx.sleep</h2>
<p><strong>syntax:</strong> <em>ngx.sleep(seconds)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>Sleeps for the specified seconds without blocking. One can specify time resolution up to 0.001 seconds (i.e., one milliseconds).</p>
<p>Behind the scene, this method makes use of the Nginx timers.</p>
<p>Since the <code class="language-plaintext highlighter-rouge">0.7.20</code> release, The <code class="language-plaintext highlighter-rouge">0</code> time argument can also be specified.</p>
<p>This method was introduced in the <code class="language-plaintext highlighter-rouge">0.5.0rc30</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxescape_uri">ngx.escape_uri</h2>
<p><strong>syntax:</strong> <em>newstr = ngx.escape_uri(str)</em></p>
<p><strong>context:</strong> <em>init_by_lua</em>, init_worker_by_lua<em>, set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.**</p>
<p>Escape <code class="language-plaintext highlighter-rouge">str</code> as a URI component.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxunescape_uri">ngx.unescape_uri</h2>
<p><strong>syntax:</strong> <em>newstr = ngx.unescape_uri(str)</em></p>
<p><strong>context:</strong> <em>init_by_lua</em>, init_worker_by_lua<em>, set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.**</p>
<p>Unescape <code class="language-plaintext highlighter-rouge">str</code> as an escaped URI component.</p>
<p>For example,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">unescape_uri</span><span class="p">(</span><span class="s2">"b%20r56+7"</span><span class="p">))</span>
</code></pre></div></div>
<p>gives the output</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>b r56 7
</code></pre></div></div>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxencode_args">ngx.encode_args</h2>
<p><strong>syntax:</strong> <em>str = ngx.encode_args(table)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.**</p>
<p>Encode the Lua table to a query args string according to the URI encoded rules.</p>
<p>For example,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">encode_args</span><span class="p">({</span><span class="n">foo</span> <span class="o">=</span> <span class="mi">3</span><span class="p">,</span> <span class="p">[</span><span class="s2">"b r"</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"hello world"</span><span class="p">})</span>
</code></pre></div></div>
<p>yields</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>foo=3&amp;b%20r=hello%20world
</code></pre></div></div>
<p>The table keys must be Lua strings.</p>
<p>Multi-value query args are also supported. Just use a Lua table for the arguments value, for example:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">encode_args</span><span class="p">({</span><span class="n">baz</span> <span class="o">=</span> <span class="p">{</span><span class="mi">32</span><span class="p">,</span> <span class="s2">"hello"</span><span class="p">}})</span>
</code></pre></div></div>
<p>gives</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>baz=32&amp;baz=hello
</code></pre></div></div>
<p>If the value table is empty and the effect is equivalent to the <code class="language-plaintext highlighter-rouge">nil</code> value.</p>
<p>Boolean argument values are also supported, for instance,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">ngx</span><span class="p">.</span><span class="n">encode_args</span><span class="p">({</span><span class="n">a</span> <span class="o">=</span> <span class="kc">true</span><span class="p">,</span> <span class="n">b</span> <span class="o">=</span> <span class="mi">1</span><span class="p">})</span>
</code></pre></div></div>
<p>yields</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>a&amp;b=1
</code></pre></div></div>
<p>If the argument value is <code class="language-plaintext highlighter-rouge">false</code>, then the effect is equivalent to the <code class="language-plaintext highlighter-rouge">nil</code> value.</p>
<p>This method was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc27</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxdecode_args">ngx.decode_args</h2>
<p><strong>syntax:</strong> <em>table = ngx.decode_args(str, max_args?)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.**</p>
<p>Decodes a URI encoded query-string into a Lua table. This is the inverse function of <a href="#ngxencode_args">ngx.encode_args</a>.</p>
<p>The optional <code class="language-plaintext highlighter-rouge">max_args</code> argument can be used to specify the maximum number of arguments parsed from the <code class="language-plaintext highlighter-rouge">str</code> argument. By default, a maximum of 100 request arguments are parsed (including those with the same name) and that additional URI arguments are silently discarded to guard against potential denial of service attacks.</p>
<p>This argument can be set to zero to remove the limit and to process all request arguments received:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">args</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">decode_args</span><span class="p">(</span><span class="n">str</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
</code></pre></div></div>
<p>Removing the <code class="language-plaintext highlighter-rouge">max_args</code> cap is strongly discouraged.</p>
<p>This method was introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc29</code>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxencode_base64">ngx.encode_base64</h2>
<p><strong>syntax:</strong> <em>newstr = ngx.encode_base64(str, no_padding?)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.**</p>
<p>Encodes <code class="language-plaintext highlighter-rouge">str</code> to a base64 digest.</p>
<p>Since the <code class="language-plaintext highlighter-rouge">0.9.16</code> release, an optional boolean-typed <code class="language-plaintext highlighter-rouge">no_padding</code> argument can be specified to control whether the base64 padding should be appended to the resulting digest (default to <code class="language-plaintext highlighter-rouge">false</code>, i.e., with padding enabled). This enables streaming base64 digest calculation by (data chunks) though it would be the callers responsibility to append an appropriate padding at the end of data stream.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxdecode_base64">ngx.decode_base64</h2>
<p><strong>syntax:</strong> <em>newstr = ngx.decode_base64(str)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.**</p>
<p>Decodes the <code class="language-plaintext highlighter-rouge">str</code> argument as a base64 digest to the raw form. Returns <code class="language-plaintext highlighter-rouge">nil</code> if <code class="language-plaintext highlighter-rouge">str</code> is not well formed.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxcrc32_short">ngx.crc32_short</h2>
<p><strong>syntax:</strong> <em>intval = ngx.crc32_short(str)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.**</p>
<p>Calculates the CRC-32 (Cyclic Redundancy Code) digest for the <code class="language-plaintext highlighter-rouge">str</code> argument.</p>
<p>This method performs better on relatively short <code class="language-plaintext highlighter-rouge">str</code> inputs (i.e., less than 30 ~ 60 bytes), as compared to <a href="#ngxcrc32_long">ngx.crc32_long</a>. The result is exactly the same as <a href="#ngxcrc32_long">ngx.crc32_long</a>.</p>
<p>Behind the scene, it is just a thin wrapper around the <code class="language-plaintext highlighter-rouge">ngx_crc32_short</code> function defined in the Nginx core.</p>
<p>This API was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc8</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxcrc32_long">ngx.crc32_long</h2>
<p><strong>syntax:</strong> <em>intval = ngx.crc32_long(str)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.**</p>
<p>Calculates the CRC-32 (Cyclic Redundancy Code) digest for the <code class="language-plaintext highlighter-rouge">str</code> argument.</p>
<p>This method performs better on relatively long <code class="language-plaintext highlighter-rouge">str</code> inputs (i.e., longer than 30 ~ 60 bytes), as compared to <a href="#ngxcrc32_short">ngx.crc32_short</a>. The result is exactly the same as <a href="#ngxcrc32_short">ngx.crc32_short</a>.</p>
<p>Behind the scene, it is just a thin wrapper around the <code class="language-plaintext highlighter-rouge">ngx_crc32_long</code> function defined in the Nginx core.</p>
<p>This API was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc8</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxhmac_sha1">ngx.hmac_sha1</h2>
<p><strong>syntax:</strong> <em>digest = ngx.hmac_sha1(secret_key, str)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.**</p>
<p>Computes the <a href="http://en.wikipedia.org/wiki/HMAC">HMAC-SHA1</a> digest of the argument <code class="language-plaintext highlighter-rouge">str</code> and turns the result using the secret key <code class="language-plaintext highlighter-rouge">&lt;secret_key&gt;</code>.</p>
<p>The raw binary form of the <code class="language-plaintext highlighter-rouge">HMAC-SHA1</code> digest will be generated, use <a href="#ngxencode_base64">ngx.encode_base64</a>, for example, to encode the result to a textual representation if desired.</p>
<p>For example,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">key</span> <span class="o">=</span> <span class="s2">"thisisverysecretstuff"</span>
<span class="kd">local</span> <span class="n">src</span> <span class="o">=</span> <span class="s2">"some string we want to sign"</span>
<span class="kd">local</span> <span class="n">digest</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">hmac_sha1</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="n">src</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">encode_base64</span><span class="p">(</span><span class="n">digest</span><span class="p">))</span>
</code></pre></div></div>
<p>yields the output</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>R/pvxzHC4NLtj7S+kXFg/NePTmk=
</code></pre></div></div>
<p>This API requires the OpenSSL library enabled in the Nginx build (usually by passing the <code class="language-plaintext highlighter-rouge">--with-http_ssl_module</code> option to the <code class="language-plaintext highlighter-rouge">./configure</code> script).</p>
<p>This function was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc29</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxmd5">ngx.md5</h2>
<p><strong>syntax:</strong> <em>digest = ngx.md5(str)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.**</p>
<p>Returns the hexadecimal representation of the MD5 digest of the <code class="language-plaintext highlighter-rouge">str</code> argument.</p>
<p>For example,</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="p">=</span> <span class="n">/md5</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'ngx.say(ngx.md5("hello"))'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>yields the output</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>5d41402abc4b2a76b9719d911017c592
</code></pre></div></div>
<p>See <a href="#ngxmd5_bin">ngx.md5_bin</a> if the raw binary MD5 digest is required.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxmd5_bin">ngx.md5_bin</h2>
<p><strong>syntax:</strong> <em>digest = ngx.md5_bin(str)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.**</p>
<p>Returns the binary form of the MD5 digest of the <code class="language-plaintext highlighter-rouge">str</code> argument.</p>
<p>See <a href="#ngxmd5">ngx.md5</a> if the hexadecimal form of the MD5 digest is required.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxsha1_bin">ngx.sha1_bin</h2>
<p><strong>syntax:</strong> <em>digest = ngx.sha1_bin(str)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.**</p>
<p>Returns the binary form of the SHA-1 digest of the <code class="language-plaintext highlighter-rouge">str</code> argument.</p>
<p>This function requires SHA-1 support in the Nginx build. (This usually just means OpenSSL should be installed while building Nginx).</p>
<p>This function was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc6</code>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxquote_sql_str">ngx.quote_sql_str</h2>
<p><strong>syntax:</strong> <em>quoted_value = ngx.quote_sql_str(raw_value)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.**</p>
<p>Returns a quoted SQL string literal according to the MySQL quoting rules.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxtoday">ngx.today</h2>
<p><strong>syntax:</strong> <em>str = ngx.today()</em></p>
<p><strong>context:</strong> <em>init_worker_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Returns current date (in the format <code class="language-plaintext highlighter-rouge">yyyy-mm-dd</code>) from the nginx cached time (no syscall involved unlike Luas date library).</p>
<p>This is the local time.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxtime">ngx.time</h2>
<p><strong>syntax:</strong> <em>secs = ngx.time()</em></p>
<p><strong>context:</strong> <em>init_worker_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Returns the elapsed seconds from the epoch for the current time stamp from the nginx cached time (no syscall involved unlike Luas date library).</p>
<p>Updates of the Nginx time cache an be forced by calling <a href="#ngxupdate_time">ngx.update_time</a> first.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxnow">ngx.now</h2>
<p><strong>syntax:</strong> <em>secs = ngx.now()</em></p>
<p><strong>context:</strong> <em>init_worker_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Returns a floating-point number for the elapsed time in seconds (including milliseconds as the decimal part) from the epoch for the current time stamp from the nginx cached time (no syscall involved unlike Luas date library).</p>
<p>You can forcibly update the Nginx time cache by calling <a href="#ngxupdate_time">ngx.update_time</a> first.</p>
<p>This API was first introduced in <code class="language-plaintext highlighter-rouge">v0.3.1rc32</code>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxupdate_time">ngx.update_time</h2>
<p><strong>syntax:</strong> <em>ngx.update_time()</em></p>
<p><strong>context:</strong> <em>init_worker_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Forcibly updates the Nginx current time cache. This call involves a syscall and thus has some overhead, so do not abuse it.</p>
<p>This API was first introduced in <code class="language-plaintext highlighter-rouge">v0.3.1rc32</code>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxlocaltime">ngx.localtime</h2>
<p><strong>syntax:</strong> <em>str = ngx.localtime()</em></p>
<p><strong>context:</strong> <em>init_worker_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Returns the current time stamp (in the format <code class="language-plaintext highlighter-rouge">yyyy-mm-dd hh:mm:ss</code>) of the nginx cached time (no syscall involved unlike Luas <a href="http://www.lua.org/manual/5.1/manual.html#pdf-os.date">os.date</a> function).</p>
<p>This is the local time.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxutctime">ngx.utctime</h2>
<p><strong>syntax:</strong> <em>str = ngx.utctime()</em></p>
<p><strong>context:</strong> <em>init_worker_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Returns the current time stamp (in the format <code class="language-plaintext highlighter-rouge">yyyy-mm-dd hh:mm:ss</code>) of the nginx cached time (no syscall involved unlike Luas <a href="http://www.lua.org/manual/5.1/manual.html#pdf-os.date">os.date</a> function).</p>
<p>This is the UTC time.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxcookie_time">ngx.cookie_time</h2>
<p><strong>syntax:</strong> <em>str = ngx.cookie_time(sec)</em></p>
<p><strong>context:</strong> <em>init_worker_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Returns a formatted string can be used as the cookie expiration time. The parameter <code class="language-plaintext highlighter-rouge">sec</code> is the time stamp in seconds (like those returned from <a href="#ngxtime">ngx.time</a>).</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">ngx.say</span><span class="s">(ngx.cookie_time(1290079655))</span>
<span class="s">--</span> <span class="s">yields</span> <span class="s">"Thu,</span> <span class="mi">18</span><span class="s">-Nov-10</span> <span class="nf">11</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">35</span> <span class="s">GMT"</span>
</code></pre></div></div>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxhttp_time">ngx.http_time</h2>
<p><strong>syntax:</strong> <em>str = ngx.http_time(sec)</em></p>
<p><strong>context:</strong> <em>init_worker_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Returns a formated string can be used as the http header time (for example, being used in <code class="language-plaintext highlighter-rouge">Last-Modified</code> header). The parameter <code class="language-plaintext highlighter-rouge">sec</code> is the time stamp in seconds (like those returned from <a href="#ngxtime">ngx.time</a>).</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">ngx.say</span><span class="s">(ngx.http_time(1290079655))</span>
<span class="s">--</span> <span class="s">yields</span> <span class="s">"Thu,</span> <span class="mi">18</span> <span class="s">Nov</span> <span class="mi">2010</span> <span class="nf">11</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">35</span> <span class="s">GMT"</span>
</code></pre></div></div>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxparse_http_time">ngx.parse_http_time</h2>
<p><strong>syntax:</strong> <em>sec = ngx.parse_http_time(str)</em></p>
<p><strong>context:</strong> <em>init_worker_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Parse the http time string (as returned by <a href="#ngxhttp_time">ngx.http_time</a>) into seconds. Returns the seconds or <code class="language-plaintext highlighter-rouge">nil</code> if the input string is in bad forms.</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">local</span> <span class="s">time</span> <span class="p">=</span> <span class="s">ngx.parse_http_time("Thu,</span> <span class="mi">18</span> <span class="s">Nov</span> <span class="mi">2010</span> <span class="nf">11</span><span class="p">:</span><span class="mi">27</span><span class="p">:</span><span class="mi">35</span> <span class="s">GMT")</span>
<span class="s">if</span> <span class="s">time</span> <span class="p">==</span> <span class="s">nil</span> <span class="s">then</span>
<span class="s">...</span>
<span class="s">end</span>
</code></pre></div></div>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxis_subrequest">ngx.is_subrequest</h2>
<p><strong>syntax:</strong> <em>value = ngx.is_subrequest</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua*, log_by_lua**</p>
<p>Returns <code class="language-plaintext highlighter-rouge">true</code> if the current request is an nginx subrequest, or <code class="language-plaintext highlighter-rouge">false</code> otherwise.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxrematch">ngx.re.match</h2>
<p><strong>syntax:</strong> <em>captures, err = ngx.re.match(subject, regex, options?, ctx?, res_table?)</em></p>
<p><strong>context:</strong> <em>init_worker_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Matches the <code class="language-plaintext highlighter-rouge">subject</code> string using the Perl compatible regular expression <code class="language-plaintext highlighter-rouge">regex</code> with the optional <code class="language-plaintext highlighter-rouge">options</code>.</p>
<p>Only the first occurrence of the match is returned, or <code class="language-plaintext highlighter-rouge">nil</code> if no match is found. In case of errors, like seeing a bad regular expression or exceeding the PCRE stack limit, <code class="language-plaintext highlighter-rouge">nil</code> and a string describing the error will be returned.</p>
<p>When a match is found, a Lua table <code class="language-plaintext highlighter-rouge">captures</code> is returned, where <code class="language-plaintext highlighter-rouge">captures[0]</code> holds the whole substring being matched, and <code class="language-plaintext highlighter-rouge">captures[1]</code> holds the first parenthesized sub-patterns capturing, <code class="language-plaintext highlighter-rouge">captures[2]</code> the second, and so on.</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">m</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">re</span><span class="p">.</span><span class="n">match</span><span class="p">(</span><span class="s2">"hello, 1234"</span><span class="p">,</span> <span class="s2">"[0-9]+"</span><span class="p">)</span>
<span class="k">if</span> <span class="n">m</span> <span class="k">then</span>
<span class="c1">-- m[0] == "1234"</span>
<span class="k">else</span>
<span class="k">if</span> <span class="n">err</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">ERR</span><span class="p">,</span> <span class="s2">"error: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"match not found"</span><span class="p">)</span>
<span class="k">end</span>
</code></pre></div></div>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">m</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">re</span><span class="p">.</span><span class="n">match</span><span class="p">(</span><span class="s2">"hello, 1234"</span><span class="p">,</span> <span class="s2">"([0-9])[0-9]+"</span><span class="p">)</span>
<span class="c1">-- m[0] == "1234"</span>
<span class="c1">-- m[1] == "1"</span>
</code></pre></div></div>
<p>Named captures are also supported since the <code class="language-plaintext highlighter-rouge">v0.7.14</code> release
and are returned in the same Lua table as key-value pairs as the numbered captures.</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">m</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">re</span><span class="p">.</span><span class="n">match</span><span class="p">(</span><span class="s2">"hello, 1234"</span><span class="p">,</span> <span class="s2">"([0-9])(?&lt;remaining&gt;[0-9]+)"</span><span class="p">)</span>
<span class="c1">-- m[0] == "1234"</span>
<span class="c1">-- m[1] == "1"</span>
<span class="c1">-- m[2] == "234"</span>
<span class="c1">-- m["remaining"] == "234"</span>
</code></pre></div></div>
<p>Unmatched subpatterns will have <code class="language-plaintext highlighter-rouge">nil</code> values in their <code class="language-plaintext highlighter-rouge">captures</code> table fields.</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">m</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">re</span><span class="p">.</span><span class="n">match</span><span class="p">(</span><span class="s2">"hello, world"</span><span class="p">,</span> <span class="s2">"(world)|(hello)|(?&lt;named&gt;howdy)"</span><span class="p">)</span>
<span class="c1">-- m[0] == "hello"</span>
<span class="c1">-- m[1] == nil</span>
<span class="c1">-- m[2] == "hello"</span>
<span class="c1">-- m[3] == nil</span>
<span class="c1">-- m["named"] == nil</span>
</code></pre></div></div>
<p>Specify <code class="language-plaintext highlighter-rouge">options</code> to control how the match operation will be performed. The following option characters are supported:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>a anchored mode (only match from the beginning)
d enable the DFA mode (or the longest token match semantics).
this requires PCRE 6.0+ or else a Lua exception will be thrown.
first introduced in ngx_lua v0.3.1rc30.
D enable duplicate named pattern support. This allows named
subpattern names to be repeated, returning the captures in
an array-like Lua table. for example,
local m = ngx.re.match("hello, world",
"(?&lt;named&gt;\w+), (?&lt;named&gt;\w+)",
"D")
-- m["named"] == {"hello", "world"}
this option was first introduced in the v0.7.14 release.
this option requires at least PCRE 8.12.
i case insensitive mode (similar to Perl's /i modifier)
j enable PCRE JIT compilation, this requires PCRE 8.21+ which
must be built with the --enable-jit option. for optimum performance,
this option should always be used together with the 'o' option.
first introduced in ngx_lua v0.3.1rc30.
J enable the PCRE Javascript compatible mode. this option was
first introduced in the v0.7.14 release. this option requires
at least PCRE 8.12.
m multi-line mode (similar to Perl's /m modifier)
o compile-once mode (similar to Perl's /o modifier),
to enable the worker-process-level compiled-regex cache
s single-line mode (similar to Perl's /s modifier)
u UTF-8 mode. this requires PCRE to be built with
the --enable-utf8 option or else a Lua exception will be thrown.
U similar to "u" but disables PCRE's UTF-8 validity check on
the subject string. first introduced in ngx_lua v0.8.1.
x extended mode (similar to Perl's /x modifier)
</code></pre></div></div>
<p>These options can be combined:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">local</span> <span class="s">m,</span> <span class="s">err</span> <span class="p">=</span> <span class="s">ngx.re.match("hello,</span> <span class="s">world",</span> <span class="s">"HEL</span> <span class="s">LO",</span> <span class="s">"ix")</span>
<span class="s">--</span> <span class="s">m[0]</span> <span class="p">==</span> <span class="s">"hello"</span>
</code></pre></div></div>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">local</span> <span class="s">m,</span> <span class="s">err</span> <span class="p">=</span> <span class="s">ngx.re.match("hello,</span> <span class="s">美好生活",</span> <span class="s">"HELLO,</span> <span class="s">(.</span><span class="p">{</span><span class="kn">2</span><span class="err">}</span><span class="s">)",</span> <span class="s">"iu")</span>
<span class="s">--</span> <span class="s">m[0]</span> <span class="p">==</span> <span class="s">"hello,</span> <span class="s">美好"</span>
<span class="s">--</span> <span class="s">m[1]</span> <span class="p">==</span> <span class="s">"美好"</span>
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">o</code> option is useful for performance tuning, because the regex pattern in question will only be compiled once, cached in the worker-process level, and shared among all requests in the current Nginx worker process. The upper limit of the regex cache can be tuned via the <a href="#lua_regex_cache_max_entries">lua_regex_cache_max_entries</a> directive.</p>
<p>The optional fourth argument, <code class="language-plaintext highlighter-rouge">ctx</code>, can be a Lua table holding an optional <code class="language-plaintext highlighter-rouge">pos</code> field. When the <code class="language-plaintext highlighter-rouge">pos</code> field in the <code class="language-plaintext highlighter-rouge">ctx</code> table argument is specified, <code class="language-plaintext highlighter-rouge">ngx.re.match</code> will start matching from that offset (starting from 1). Regardless of the presence of the <code class="language-plaintext highlighter-rouge">pos</code> field in the <code class="language-plaintext highlighter-rouge">ctx</code> table, <code class="language-plaintext highlighter-rouge">ngx.re.match</code> will always set this <code class="language-plaintext highlighter-rouge">pos</code> field to the position <em>after</em> the substring matched by the whole pattern in case of a successful match. When match fails, the <code class="language-plaintext highlighter-rouge">ctx</code> table will be left intact.</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">ctx</span> <span class="o">=</span> <span class="p">{}</span>
<span class="kd">local</span> <span class="n">m</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">re</span><span class="p">.</span><span class="n">match</span><span class="p">(</span><span class="s2">"1234, hello"</span><span class="p">,</span> <span class="s2">"[0-9]+"</span><span class="p">,</span> <span class="s2">""</span><span class="p">,</span> <span class="n">ctx</span><span class="p">)</span>
<span class="c1">-- m[0] = "1234"</span>
<span class="c1">-- ctx.pos == 5</span>
</code></pre></div></div>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">ctx</span> <span class="o">=</span> <span class="p">{</span> <span class="n">pos</span> <span class="o">=</span> <span class="mi">2</span> <span class="p">}</span>
<span class="kd">local</span> <span class="n">m</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">re</span><span class="p">.</span><span class="n">match</span><span class="p">(</span><span class="s2">"1234, hello"</span><span class="p">,</span> <span class="s2">"[0-9]+"</span><span class="p">,</span> <span class="s2">""</span><span class="p">,</span> <span class="n">ctx</span><span class="p">)</span>
<span class="c1">-- m[0] = "34"</span>
<span class="c1">-- ctx.pos == 5</span>
</code></pre></div></div>
<p>The <code class="language-plaintext highlighter-rouge">ctx</code> table argument combined with the <code class="language-plaintext highlighter-rouge">a</code> regex modifier can be used to construct a lexer atop <code class="language-plaintext highlighter-rouge">ngx.re.match</code>.</p>
<p>Note that, the <code class="language-plaintext highlighter-rouge">options</code> argument is not optional when the <code class="language-plaintext highlighter-rouge">ctx</code> argument is specified and that the empty Lua string (<code class="language-plaintext highlighter-rouge">""</code>) must be used as placeholder for <code class="language-plaintext highlighter-rouge">options</code> if no meaningful regex options are required.</p>
<p>This method requires the PCRE library enabled in Nginx. (<a href="#special-escaping-sequences">Known Issue With Special Escaping Sequences</a>).</p>
<p>To confirm that PCRE JIT is enabled, activate the Nginx debug log by adding the <code class="language-plaintext highlighter-rouge">--with-debug</code> option to Nginx or ngx_openrestys <code class="language-plaintext highlighter-rouge">./configure</code> script. Then, enable the “debug” error log level in <code class="language-plaintext highlighter-rouge">error_log</code> directive. The following message will be generated if PCRE JIT is enabled:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>pcre JIT compiling result: 1
</code></pre></div></div>
<p>Starting from the <code class="language-plaintext highlighter-rouge">0.9.4</code> release, this function also accepts a 5th argument, <code class="language-plaintext highlighter-rouge">res_table</code>, for letting the caller supply the Lua table used to hold all the capturing results. Starting from <code class="language-plaintext highlighter-rouge">0.9.6</code>, it is the callers responsibility to ensure this table is empty. This is very useful for recycling Lua tables and saving GC and table allocation overhead.</p>
<p>This feature was introduced in the <code class="language-plaintext highlighter-rouge">v0.2.1rc11</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxrefind">ngx.re.find</h2>
<p><strong>syntax:</strong> <em>from, to, err = ngx.re.find(subject, regex, options?, ctx?, nth?)</em></p>
<p><strong>context:</strong> <em>init_worker_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Similar to <a href="#ngxrematch">ngx.re.match</a> but only returns the begining index (<code class="language-plaintext highlighter-rouge">from</code>) and end index (<code class="language-plaintext highlighter-rouge">to</code>) of the matched substring. The returned indexes are 1-based and can be fed directly into the <a href="http://www.lua.org/manual/5.1/manual.html#pdf-string.sub">string.sub</a> API function to obtain the matched substring.</p>
<p>In case of errors (like bad regexes or any PCRE runtime errors), this API function returns two <code class="language-plaintext highlighter-rouge">nil</code> values followed by a string describing the error.</p>
<p>If no match is found, this function just returns a <code class="language-plaintext highlighter-rouge">nil</code> value.</p>
<p>Below is an example:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">s</span> <span class="o">=</span> <span class="s2">"hello, 1234"</span>
<span class="kd">local</span> <span class="n">from</span><span class="p">,</span> <span class="n">to</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">re</span><span class="p">.</span><span class="n">find</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="s2">"([0-9]+)"</span><span class="p">,</span> <span class="s2">"jo"</span><span class="p">)</span>
<span class="k">if</span> <span class="n">from</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"from: "</span><span class="p">,</span> <span class="n">from</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"to: "</span><span class="p">,</span> <span class="n">to</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"matched: "</span><span class="p">,</span> <span class="nb">string.sub</span><span class="p">(</span><span class="n">s</span><span class="p">,</span> <span class="n">from</span><span class="p">,</span> <span class="n">to</span><span class="p">))</span>
<span class="k">else</span>
<span class="k">if</span> <span class="n">err</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"error: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"not matched!"</span><span class="p">)</span>
<span class="k">end</span>
</code></pre></div></div>
<p>This example produces the output</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>from: 8
to: 11
matched: 1234
</code></pre></div></div>
<p>Because this API function does not create new Lua strings nor new Lua tables, it is much faster than <a href="#ngxrematch">ngx.re.match</a>. It should be used wherever possible.</p>
<p>Since the <code class="language-plaintext highlighter-rouge">0.9.3</code> release, an optional 5th argument, <code class="language-plaintext highlighter-rouge">nth</code>, is supported to specify which (submatch) captures indexes to return. When <code class="language-plaintext highlighter-rouge">nth</code> is 0 (which is the default), the indexes for the whole matched substring is returned; when <code class="language-plaintext highlighter-rouge">nth</code> is 1, then the 1st submatch captures indexes are returned; when <code class="language-plaintext highlighter-rouge">nth</code> is 2, then the 2nd submatch capture is returned, and so on. When the specified submatch does not have a match, then two <code class="language-plaintext highlighter-rouge">nil</code> values will be returned. Below is an example for this:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">str</span> <span class="o">=</span> <span class="s2">"hello, 1234"</span>
<span class="kd">local</span> <span class="n">from</span><span class="p">,</span> <span class="n">to</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">re</span><span class="p">.</span><span class="n">find</span><span class="p">(</span><span class="n">str</span><span class="p">,</span> <span class="s2">"([0-9])([0-9]+)"</span><span class="p">,</span> <span class="s2">"jo"</span><span class="p">,</span> <span class="kc">nil</span><span class="p">,</span> <span class="mi">2</span><span class="p">)</span>
<span class="k">if</span> <span class="n">from</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"matched 2nd submatch: "</span><span class="p">,</span> <span class="nb">string.sub</span><span class="p">(</span><span class="n">str</span><span class="p">,</span> <span class="n">from</span><span class="p">,</span> <span class="n">to</span><span class="p">))</span> <span class="c1">-- yields "234"</span>
<span class="k">end</span>
</code></pre></div></div>
<p>This API function was first introduced in the <code class="language-plaintext highlighter-rouge">v0.9.2</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxregmatch">ngx.re.gmatch</h2>
<p><strong>syntax:</strong> <em>iterator, err = ngx.re.gmatch(subject, regex, options?)</em></p>
<p><strong>context:</strong> <em>init_worker_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Similar to <a href="#ngxrematch">ngx.re.match</a>, but returns a Lua iterator instead, so as to let the user programmer iterate all the matches over the <code class="language-plaintext highlighter-rouge">&lt;subject&gt;</code> string argument with the PCRE <code class="language-plaintext highlighter-rouge">regex</code>.</p>
<p>In case of errors, like seeing an ill-formed regular expression, <code class="language-plaintext highlighter-rouge">nil</code> and a string describing the error will be returned.</p>
<p>Here is a small example to demonstrate its basic usage:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">iterator</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">re</span><span class="p">.</span><span class="n">gmatch</span><span class="p">(</span><span class="s2">"hello, world!"</span><span class="p">,</span> <span class="s2">"([a-z]+)"</span><span class="p">,</span> <span class="s2">"i"</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">iterator</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">ERR</span><span class="p">,</span> <span class="s2">"error: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
<span class="kd">local</span> <span class="n">m</span>
<span class="n">m</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">iterator</span><span class="p">()</span> <span class="c1">-- m[0] == m[1] == "hello"</span>
<span class="k">if</span> <span class="n">err</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">ERR</span><span class="p">,</span> <span class="s2">"error: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
<span class="n">m</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">iterator</span><span class="p">()</span> <span class="c1">-- m[0] == m[1] == "world"</span>
<span class="k">if</span> <span class="n">err</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">ERR</span><span class="p">,</span> <span class="s2">"error: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
<span class="n">m</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">iterator</span><span class="p">()</span> <span class="c1">-- m == nil</span>
<span class="k">if</span> <span class="n">err</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">ERR</span><span class="p">,</span> <span class="s2">"error: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
</code></pre></div></div>
<p>More often we just put it into a Lua loop:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">it</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">re</span><span class="p">.</span><span class="n">gmatch</span><span class="p">(</span><span class="s2">"hello, world!"</span><span class="p">,</span> <span class="s2">"([a-z]+)"</span><span class="p">,</span> <span class="s2">"i"</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">it</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">ERR</span><span class="p">,</span> <span class="s2">"error: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
<span class="k">while</span> <span class="kc">true</span> <span class="k">do</span>
<span class="kd">local</span> <span class="n">m</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">it</span><span class="p">()</span>
<span class="k">if</span> <span class="n">err</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">ERR</span><span class="p">,</span> <span class="s2">"error: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">m</span> <span class="k">then</span>
<span class="c1">-- no match found (any more)</span>
<span class="k">break</span>
<span class="k">end</span>
<span class="c1">-- found a match</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="n">m</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
<span class="k">end</span>
</code></pre></div></div>
<p>The optional <code class="language-plaintext highlighter-rouge">options</code> argument takes exactly the same semantics as the <a href="#ngxrematch">ngx.re.match</a> method.</p>
<p>The current implementation requires that the iterator returned should only be used in a single request. That is, one should <em>not</em> assign it to a variable belonging to persistent namespace like a Lua package.</p>
<p>This method requires the PCRE library enabled in Nginx. (<a href="#special-escaping-sequences">Known Issue With Special Escaping Sequences</a>).</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.2.1rc12</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxresub">ngx.re.sub</h2>
<p><strong>syntax:</strong> <em>newstr, n, err = ngx.re.sub(subject, regex, replace, options?)</em></p>
<p><strong>context:</strong> <em>init_worker_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Substitutes the first match of the Perl compatible regular expression <code class="language-plaintext highlighter-rouge">regex</code> on the <code class="language-plaintext highlighter-rouge">subject</code> argument string with the string or function argument <code class="language-plaintext highlighter-rouge">replace</code>. The optional <code class="language-plaintext highlighter-rouge">options</code> argument has exactly the same meaning as in <a href="#ngxrematch">ngx.re.match</a>.</p>
<p>This method returns the resulting new string as well as the number of successful substitutions. In case of failures, like syntax errors in the regular expressions or the <code class="language-plaintext highlighter-rouge">&lt;replace&gt;</code> string argument, it will return <code class="language-plaintext highlighter-rouge">nil</code> and a string describing the error.</p>
<p>When the <code class="language-plaintext highlighter-rouge">replace</code> is a string, then it is treated as a special template for string replacement. For example,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">newstr</span><span class="p">,</span> <span class="n">n</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">re</span><span class="p">.</span><span class="n">sub</span><span class="p">(</span><span class="s2">"hello, 1234"</span><span class="p">,</span> <span class="s2">"([0-9])[0-9]"</span><span class="p">,</span> <span class="s2">"[$0][$1]"</span><span class="p">)</span>
<span class="k">if</span> <span class="n">newstr</span> <span class="k">then</span>
<span class="c1">-- newstr == "hello, [12][1]34"</span>
<span class="c1">-- n == 1</span>
<span class="k">else</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">ERR</span><span class="p">,</span> <span class="s2">"error: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
</code></pre></div></div>
<p>where <code class="language-plaintext highlighter-rouge">$0</code> referring to the whole substring matched by the pattern and <code class="language-plaintext highlighter-rouge">$1</code> referring to the first parenthesized capturing substring.</p>
<p>Curly braces can also be used to disambiguate variable names from the background string literals:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">newstr</span><span class="p">,</span> <span class="n">n</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">re</span><span class="p">.</span><span class="n">sub</span><span class="p">(</span><span class="s2">"hello, 1234"</span><span class="p">,</span> <span class="s2">"[0-9]"</span><span class="p">,</span> <span class="s2">"${0}00"</span><span class="p">)</span>
<span class="c1">-- newstr == "hello, 100234"</span>
<span class="c1">-- n == 1</span>
</code></pre></div></div>
<p>Literal dollar sign characters (<code class="language-plaintext highlighter-rouge">$</code>) in the <code class="language-plaintext highlighter-rouge">replace</code> string argument can be escaped by another dollar sign, for instance,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">newstr</span><span class="p">,</span> <span class="n">n</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">re</span><span class="p">.</span><span class="n">sub</span><span class="p">(</span><span class="s2">"hello, 1234"</span><span class="p">,</span> <span class="s2">"[0-9]"</span><span class="p">,</span> <span class="s2">"$$"</span><span class="p">)</span>
<span class="c1">-- newstr == "hello, $234"</span>
<span class="c1">-- n == 1</span>
</code></pre></div></div>
<p>Do not use backlashes to escape dollar signs; it will not work as expected.</p>
<p>When the <code class="language-plaintext highlighter-rouge">replace</code> argument is of type “function”, then it will be invoked with the “match table” as the argument to generate the replace string literal for substitution. The “match table” fed into the <code class="language-plaintext highlighter-rouge">replace</code> function is exactly the same as the return value of <a href="#ngxrematch">ngx.re.match</a>. Here is an example:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">func</span> <span class="o">=</span> <span class="k">function</span> <span class="p">(</span><span class="n">m</span><span class="p">)</span>
<span class="k">return</span> <span class="s2">"["</span> <span class="o">..</span> <span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">..</span> <span class="s2">"]["</span> <span class="o">..</span> <span class="n">m</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">..</span> <span class="s2">"]"</span>
<span class="k">end</span>
<span class="kd">local</span> <span class="n">newstr</span><span class="p">,</span> <span class="n">n</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">re</span><span class="p">.</span><span class="n">sub</span><span class="p">(</span><span class="s2">"hello, 1234"</span><span class="p">,</span> <span class="s2">"( [0-9] ) [0-9]"</span><span class="p">,</span> <span class="n">func</span><span class="p">,</span> <span class="s2">"x"</span><span class="p">)</span>
<span class="c1">-- newstr == "hello, [12][1]34"</span>
<span class="c1">-- n == 1</span>
</code></pre></div></div>
<p>The dollar sign characters in the return value of the <code class="language-plaintext highlighter-rouge">replace</code> function argument are not special at all.</p>
<p>This method requires the PCRE library enabled in Nginx. (<a href="#special-escaping-sequences">Known Issue With Special Escaping Sequences</a>).</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.2.1rc13</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxregsub">ngx.re.gsub</h2>
<p><strong>syntax:</strong> <em>newstr, n, err = ngx.re.gsub(subject, regex, replace, options?)</em></p>
<p><strong>context:</strong> <em>init_worker_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Just like <a href="#ngxresub">ngx.re.sub</a>, but does global substitution.</p>
<p>Here is some examples:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">newstr</span><span class="p">,</span> <span class="n">n</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">re</span><span class="p">.</span><span class="nb">gsub</span><span class="p">(</span><span class="sr">"hello, world"</span><span class="p">,</span> <span class="sr">"</span><span class="se">([</span><span class="sr">a-z</span><span class="se">])[</span><span class="sr">a-z</span><span class="se">]</span><span class="sr">+"</span><span class="p">,</span> <span class="sr">"</span><span class="se">[</span><span class="sr">$0,$1</span><span class="se">]</span><span class="sr">"</span><span class="p">,</span> <span class="sr">"i"</span><span class="p">)</span>
<span class="k">if</span> <span class="n">newstr</span> <span class="k">then</span>
<span class="c1">-- newstr == "[hello,h], [world,w]"</span>
<span class="c1">-- n == 2</span>
<span class="k">else</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">ERR</span><span class="p">,</span> <span class="s2">"error: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
</code></pre></div></div>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">func</span> <span class="o">=</span> <span class="k">function</span> <span class="p">(</span><span class="n">m</span><span class="p">)</span>
<span class="k">return</span> <span class="s2">"["</span> <span class="o">..</span> <span class="n">m</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">..</span> <span class="s2">","</span> <span class="o">..</span> <span class="n">m</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">..</span> <span class="s2">"]"</span>
<span class="k">end</span>
<span class="kd">local</span> <span class="n">newstr</span><span class="p">,</span> <span class="n">n</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">re</span><span class="p">.</span><span class="nb">gsub</span><span class="p">(</span><span class="sr">"hello, world"</span><span class="p">,</span> <span class="sr">"</span><span class="se">([</span><span class="sr">a-z</span><span class="se">])[</span><span class="sr">a-z</span><span class="se">]</span><span class="sr">+"</span><span class="p">,</span> <span class="err">func</span><span class="p">,</span> <span class="sr">"i"</span><span class="p">)</span>
<span class="c1">-- newstr == "[hello,h], [world,w]"</span>
<span class="c1">-- n == 2</span>
</code></pre></div></div>
<p>This method requires the PCRE library enabled in Nginx. (<a href="#special-escaping-sequences">Known Issue With Special Escaping Sequences</a>).</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.2.1rc15</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxshareddict">ngx.shared.DICT</h2>
<p><strong>syntax:</strong> <em>dict = ngx.shared.DICT</em></p>
<p><strong>syntax:</strong> <em>dict = ngx.shared[name_var]</em></p>
<p><strong>context:</strong> <em>init_by_lua</em>, init_worker_by_lua<em>, set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.**</p>
<p>Fetching the shm-based Lua dictionary object for the shared memory zone named <code class="language-plaintext highlighter-rouge">DICT</code> defined by the <a href="#lua_shared_dict">lua_shared_dict</a> directive.</p>
<p>Shared memory zones are always shared by all the nginx worker processes in the current nginx server instance.</p>
<p>The resulting object <code class="language-plaintext highlighter-rouge">dict</code> has the following methods:</p>
<ul>
<li><a href="#ngxshareddictget">get</a></li>
<li><a href="#ngxshareddictget_stale">get_stale</a></li>
<li><a href="#ngxshareddictset">set</a></li>
<li><a href="#ngxshareddictsafe_set">safe_set</a></li>
<li><a href="#ngxshareddictadd">add</a></li>
<li><a href="#ngxshareddictsafe_add">safe_add</a></li>
<li><a href="#ngxshareddictreplace">replace</a></li>
<li><a href="#ngxshareddictdelete">delete</a></li>
<li><a href="#ngxshareddictincr">incr</a></li>
<li><a href="#ngxshareddictflush_all">flush_all</a></li>
<li><a href="#ngxshareddictflush_expired">flush_expired</a></li>
<li><a href="#ngxshareddictget_keys">get_keys</a></li>
</ul>
<p>Here is an example:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">http</span> <span class="p">{</span>
<span class="kn">lua_shared_dict</span> <span class="s">dogs</span> <span class="mi">10m</span><span class="p">;</span>
<span class="kn">server</span> <span class="p">{</span>
<span class="kn">location</span> <span class="n">/set</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">dogs</span> <span class="p">=</span> <span class="s">ngx.shared.dogs</span>
<span class="s">dogs:set("Jim",</span> <span class="mi">8</span><span class="s">)</span>
<span class="s">ngx.say("STORED")</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="kn">location</span> <span class="n">/get</span> <span class="p">{</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">dogs</span> <span class="p">=</span> <span class="s">ngx.shared.dogs</span>
<span class="s">ngx.say(dogs:get("Jim"))</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Let us test it:</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="nv">$ </span>curl localhost/set
STORED
<span class="nv">$ </span>curl localhost/get
8
<span class="nv">$ </span>curl localhost/get
8
</code></pre></div></div>
<p>The number <code class="language-plaintext highlighter-rouge">8</code> will be consistently output when accessing <code class="language-plaintext highlighter-rouge">/get</code> regardless of how many Nginx workers there are because the <code class="language-plaintext highlighter-rouge">dogs</code> dictionary resides in the shared memory and visible to <em>all</em> of the worker processes.</p>
<p>The shared dictionary will retain its contents through a server config reload (either by sending the <code class="language-plaintext highlighter-rouge">HUP</code> signal to the Nginx process or by using the <code class="language-plaintext highlighter-rouge">-s reload</code> command-line option).</p>
<p>The contents in the dictionary storage will be lost, however, when the Nginx server quits.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc22</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxshareddictget">ngx.shared.DICT.get</h2>
<p><strong>syntax:</strong> <em>value, flags = ngx.shared.DICT:get(key)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.**</p>
<p>Retrieving the value in the dictionary <a href="#ngxshareddict">ngx.shared.DICT</a> for the key <code class="language-plaintext highlighter-rouge">key</code>. If the key does not exist or has been expired, then <code class="language-plaintext highlighter-rouge">nil</code> will be returned.</p>
<p>In case of errors, <code class="language-plaintext highlighter-rouge">nil</code> and a string describing the error will be returned.</p>
<p>The value returned will have the original data type when they were inserted into the dictionary, for example, Lua booleans, numbers, or strings.</p>
<p>The first argument to this method must be the dictionary object itself, for example,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">cats</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">shared</span><span class="p">.</span><span class="n">cats</span>
<span class="kd">local</span> <span class="n">value</span><span class="p">,</span> <span class="n">flags</span> <span class="o">=</span> <span class="n">cats</span><span class="p">.</span><span class="n">get</span><span class="p">(</span><span class="n">cats</span><span class="p">,</span> <span class="s2">"Marry"</span><span class="p">)</span>
</code></pre></div></div>
<p>or use Luas syntactic sugar for method calls:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">cats</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">shared</span><span class="p">.</span><span class="n">cats</span>
<span class="kd">local</span> <span class="n">value</span><span class="p">,</span> <span class="n">flags</span> <span class="o">=</span> <span class="n">cats</span><span class="p">:</span><span class="n">get</span><span class="p">(</span><span class="s2">"Marry"</span><span class="p">)</span>
</code></pre></div></div>
<p>These two forms are fundamentally equivalent.</p>
<p>If the user flags is <code class="language-plaintext highlighter-rouge">0</code> (the default), then no flags value will be returned.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc22</code> release.</p>
<p>See also <a href="#ngxshareddict">ngx.shared.DICT</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxshareddictget_stale">ngx.shared.DICT.get_stale</h2>
<p><strong>syntax:</strong> <em>value, flags, stale = ngx.shared.DICT:get_stale(key)</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.**</p>
<p>Similar to the <a href="#ngxshareddictget">get</a> method but returns the value even if the key has already expired.</p>
<p>Returns a 3rd value, <code class="language-plaintext highlighter-rouge">stale</code>, indicating whether the key has expired or not.</p>
<p>Note that the value of an expired key is not guaranteed to be available so one should never rely on the availability of expired items.</p>
<p>This method was first introduced in the <code class="language-plaintext highlighter-rouge">0.8.6</code> release.</p>
<p>See also <a href="#ngxshareddict">ngx.shared.DICT</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxshareddictset">ngx.shared.DICT.set</h2>
<p><strong>syntax:</strong> <em>success, err, forcible = ngx.shared.DICT:set(key, value, exptime?, flags?)</em></p>
<p><strong>context:</strong> <em>init_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Unconditionally sets a key-value pair into the shm-based dictionary <a href="#ngxshareddict">ngx.shared.DICT</a>. Returns three values:</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">success</code>: boolean value to indicate whether the key-value pair is stored or not.</li>
<li><code class="language-plaintext highlighter-rouge">err</code>: textual error message, can be <code class="language-plaintext highlighter-rouge">"no memory"</code>.</li>
<li><code class="language-plaintext highlighter-rouge">forcible</code>: a boolean value to indicate whether other valid items have been removed forcibly when out of storage in the shared memory zone.</li>
</ul>
<p>The <code class="language-plaintext highlighter-rouge">value</code> argument inserted can be Lua booleans, numbers, strings, or <code class="language-plaintext highlighter-rouge">nil</code>. Their value type will also be stored into the dictionary and the same data type can be retrieved later via the <a href="#ngxshareddictget">get</a> method.</p>
<p>The optional <code class="language-plaintext highlighter-rouge">exptime</code> argument specifies expiration time (in seconds) for the inserted key-value pair. The time resolution is <code class="language-plaintext highlighter-rouge">0.001</code> seconds. If the <code class="language-plaintext highlighter-rouge">exptime</code> takes the value <code class="language-plaintext highlighter-rouge">0</code> (which is the default), then the item will never be expired.</p>
<p>The optional <code class="language-plaintext highlighter-rouge">flags</code> argument specifies a user flags value associated with the entry to be stored. It can also be retrieved later with the value. The user flags is stored as an unsigned 32-bit integer internally. Defaults to <code class="language-plaintext highlighter-rouge">0</code>. The user flags argument was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc2</code> release.</p>
<p>When it fails to allocate memory for the current key-value item, then <code class="language-plaintext highlighter-rouge">set</code> will try removing existing items in the storage according to the Least-Recently Used (LRU) algorithm. Note that, LRU takes priority over expiration time here. If up to tens of existing items have been removed and the storage left is still insufficient (either due to the total capacity limit specified by <a href="#lua_shared_dict">lua_shared_dict</a> or memory segmentation), then the <code class="language-plaintext highlighter-rouge">err</code> return value will be <code class="language-plaintext highlighter-rouge">no memory</code> and <code class="language-plaintext highlighter-rouge">success</code> will be <code class="language-plaintext highlighter-rouge">false</code>.</p>
<p>If this method succeeds in storing the current item by forcibly removing other not-yet-expired items in the dictionary via LRU, the <code class="language-plaintext highlighter-rouge">forcible</code> return value will be <code class="language-plaintext highlighter-rouge">true</code>. If it stores the item without forcibly removing other valid items, then the return value <code class="language-plaintext highlighter-rouge">forcible</code> will be <code class="language-plaintext highlighter-rouge">false</code>.</p>
<p>The first argument to this method must be the dictionary object itself, for example,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">cats</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">shared</span><span class="p">.</span><span class="n">cats</span>
<span class="kd">local</span> <span class="n">succ</span><span class="p">,</span> <span class="n">err</span><span class="p">,</span> <span class="n">forcible</span> <span class="o">=</span> <span class="n">cats</span><span class="p">.</span><span class="n">set</span><span class="p">(</span><span class="n">cats</span><span class="p">,</span> <span class="s2">"Marry"</span><span class="p">,</span> <span class="s2">"it is a nice cat!"</span><span class="p">)</span>
</code></pre></div></div>
<p>or use Luas syntactic sugar for method calls:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">cats</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">shared</span><span class="p">.</span><span class="n">cats</span>
<span class="kd">local</span> <span class="n">succ</span><span class="p">,</span> <span class="n">err</span><span class="p">,</span> <span class="n">forcible</span> <span class="o">=</span> <span class="n">cats</span><span class="p">:</span><span class="n">set</span><span class="p">(</span><span class="s2">"Marry"</span><span class="p">,</span> <span class="s2">"it is a nice cat!"</span><span class="p">)</span>
</code></pre></div></div>
<p>These two forms are fundamentally equivalent.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc22</code> release.</p>
<p>Please note that while internally the key-value pair is set atomically, the atomicity does not go across the method call boundary.</p>
<p>See also <a href="#ngxshareddict">ngx.shared.DICT</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxshareddictsafe_set">ngx.shared.DICT.safe_set</h2>
<p><strong>syntax:</strong> <em>ok, err = ngx.shared.DICT:safe_set(key, value, exptime?, flags?)</em></p>
<p><strong>context:</strong> <em>init_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Similar to the <a href="#ngxshareddictset">set</a> method, but never overrides the (least recently used) unexpired items in the store when running out of storage in the shared memory zone. In this case, it will immediately return <code class="language-plaintext highlighter-rouge">nil</code> and the string “no memory”.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.7.18</code> release.</p>
<p>See also <a href="#ngxshareddict">ngx.shared.DICT</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxshareddictadd">ngx.shared.DICT.add</h2>
<p><strong>syntax:</strong> <em>success, err, forcible = ngx.shared.DICT:add(key, value, exptime?, flags?)</em></p>
<p><strong>context:</strong> <em>init_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Just like the <a href="#ngxshareddictset">set</a> method, but only stores the key-value pair into the dictionary <a href="#ngxshareddict">ngx.shared.DICT</a> if the key does <em>not</em> exist.</p>
<p>If the <code class="language-plaintext highlighter-rouge">key</code> argument already exists in the dictionary (and not expired for sure), the <code class="language-plaintext highlighter-rouge">success</code> return value will be <code class="language-plaintext highlighter-rouge">false</code> and the <code class="language-plaintext highlighter-rouge">err</code> return value will be <code class="language-plaintext highlighter-rouge">"exists"</code>.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc22</code> release.</p>
<p>See also <a href="#ngxshareddict">ngx.shared.DICT</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxshareddictsafe_add">ngx.shared.DICT.safe_add</h2>
<p><strong>syntax:</strong> <em>ok, err = ngx.shared.DICT:safe_add(key, value, exptime?, flags?)</em></p>
<p><strong>context:</strong> <em>init_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Similar to the <a href="#ngxshareddictadd">add</a> method, but never overrides the (least recently used) unexpired items in the store when running out of storage in the shared memory zone. In this case, it will immediately return <code class="language-plaintext highlighter-rouge">nil</code> and the string “no memory”.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.7.18</code> release.</p>
<p>See also <a href="#ngxshareddict">ngx.shared.DICT</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxshareddictreplace">ngx.shared.DICT.replace</h2>
<p><strong>syntax:</strong> <em>success, err, forcible = ngx.shared.DICT:replace(key, value, exptime?, flags?)</em></p>
<p><strong>context:</strong> <em>init_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Just like the <a href="#ngxshareddictset">set</a> method, but only stores the key-value pair into the dictionary <a href="#ngxshareddict">ngx.shared.DICT</a> if the key <em>does</em> exist.</p>
<p>If the <code class="language-plaintext highlighter-rouge">key</code> argument does <em>not</em> exist in the dictionary (or expired already), the <code class="language-plaintext highlighter-rouge">success</code> return value will be <code class="language-plaintext highlighter-rouge">false</code> and the <code class="language-plaintext highlighter-rouge">err</code> return value will be <code class="language-plaintext highlighter-rouge">"not found"</code>.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc22</code> release.</p>
<p>See also <a href="#ngxshareddict">ngx.shared.DICT</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxshareddictdelete">ngx.shared.DICT.delete</h2>
<p><strong>syntax:</strong> <em>ngx.shared.DICT:delete(key)</em></p>
<p><strong>context:</strong> <em>init_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Unconditionally removes the key-value pair from the shm-based dictionary <a href="#ngxshareddict">ngx.shared.DICT</a>.</p>
<p>It is equivalent to <code class="language-plaintext highlighter-rouge">ngx.shared.DICT:set(key, nil)</code>.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc22</code> release.</p>
<p>See also <a href="#ngxshareddict">ngx.shared.DICT</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxshareddictincr">ngx.shared.DICT.incr</h2>
<p><strong>syntax:</strong> <em>newval, err = ngx.shared.DICT:incr(key, value)</em></p>
<p><strong>context:</strong> <em>init_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Increments the (numerical) value for <code class="language-plaintext highlighter-rouge">key</code> in the shm-based dictionary <a href="#ngxshareddict">ngx.shared.DICT</a> by the step value <code class="language-plaintext highlighter-rouge">value</code>. Returns the new resulting number if the operation is successfully completed or <code class="language-plaintext highlighter-rouge">nil</code> and an error message otherwise.</p>
<p>The key must already exist in the dictionary, otherwise it will return <code class="language-plaintext highlighter-rouge">nil</code> and <code class="language-plaintext highlighter-rouge">"not found"</code>.</p>
<p>If the original value is not a valid Lua number in the dictionary, it will return <code class="language-plaintext highlighter-rouge">nil</code> and <code class="language-plaintext highlighter-rouge">"not a number"</code>.</p>
<p>The <code class="language-plaintext highlighter-rouge">value</code> argument can be any valid Lua numbers, like negative numbers or floating-point numbers.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.3.1rc22</code> release.</p>
<p>See also <a href="#ngxshareddict">ngx.shared.DICT</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxshareddictflush_all">ngx.shared.DICT.flush_all</h2>
<p><strong>syntax:</strong> <em>ngx.shared.DICT:flush_all()</em></p>
<p><strong>context:</strong> <em>init_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Flushes out all the items in the dictionary. This method does not actuall free up all the memory blocks in the dictionary but just marks all the existing items as expired.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc17</code> release.</p>
<p>See also <a href="#ngxshareddictflush_expired">ngx.shared.DICT.flush_expired</a> and <a href="#ngxshareddict">ngx.shared.DICT</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxshareddictflush_expired">ngx.shared.DICT.flush_expired</h2>
<p><strong>syntax:</strong> <em>flushed = ngx.shared.DICT:flush_expired(max_count?)</em></p>
<p><strong>context:</strong> <em>init_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Flushes out the expired items in the dictionary, up to the maximal number specified by the optional <code class="language-plaintext highlighter-rouge">max_count</code> argument. When the <code class="language-plaintext highlighter-rouge">max_count</code> argument is given <code class="language-plaintext highlighter-rouge">0</code> or not given at all, then it means unlimited. Returns the number of items that have actually been flushed.</p>
<p>Unlike the <a href="#ngxshareddictflush_all">flush_all</a> method, this method actually free up the memory used by the expired items.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.6.3</code> release.</p>
<p>See also <a href="#ngxshareddictflush_all">ngx.shared.DICT.flush_all</a> and <a href="#ngxshareddict">ngx.shared.DICT</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxshareddictget_keys">ngx.shared.DICT.get_keys</h2>
<p><strong>syntax:</strong> <em>keys = ngx.shared.DICT:get_keys(max_count?)</em></p>
<p><strong>context:</strong> <em>init_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Fetch a list of the keys from the dictionary, up to <code class="language-plaintext highlighter-rouge">&lt;max_count&gt;</code>.</p>
<p>By default, only the first 1024 keys (if any) are returned. When the <code class="language-plaintext highlighter-rouge">&lt;max_count&gt;</code> argument is given the value <code class="language-plaintext highlighter-rouge">0</code>, then all the keys will be returned even there is more than 1024 keys in the dictionary.</p>
<p><strong>WARNING</strong> Be careful when calling this method on dictionaries with a really huge number of keys. This method may lock the dictionary for quite a while and block all the nginx worker processes that are trying to access the dictionary.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.7.3</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxsocketudp">ngx.socket.udp</h2>
<p><strong>syntax:</strong> <em>udpsock = ngx.socket.udp()</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>Creates and returns a UDP or datagram-oriented unix domain socket object (also known as one type of the “cosocket” objects). The following methods are supported on this object:</p>
<ul>
<li><a href="#udpsocksetpeername">setpeername</a></li>
<li><a href="#udpsocksend">send</a></li>
<li><a href="#udpsockreceive">receive</a></li>
<li><a href="#udpsockclose">close</a></li>
<li><a href="#udpsocksettimeout">settimeout</a></li>
</ul>
<p>It is intended to be compatible with the UDP API of the <a href="http://w3.impa.br/~diego/software/luasocket/udp.html">LuaSocket</a> library but is 100% nonblocking out of the box.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.7</code> release.</p>
<p>See also <a href="#ngxsockettcp">ngx.socket.tcp</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="udpsocksetpeername">udpsock:setpeername</h2>
<p><strong>syntax:</strong> <em>ok, err = udpsock:setpeername(host, port)</em></p>
<p><strong>syntax:</strong> <em>ok, err = udpsock:setpeername(“unix:/path/to/unix-domain.socket”)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>Attempts to connect a UDP socket object to a remote server or to a datagram unix domain socket file. Because the datagram protocol is actually connection-less, this method does not really establish a “connection”, but only just set the name of the remote peer for subsequent read/write operations.</p>
<p>Both IP addresses and domain names can be specified as the <code class="language-plaintext highlighter-rouge">host</code> argument. In case of domain names, this method will use Nginx cores dynamic resolver to parse the domain name without blocking and it is required to configure the <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#resolver">resolver</a> directive in the <code class="language-plaintext highlighter-rouge">nginx.conf</code> file like this:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">resolver</span> <span class="mf">8.8</span><span class="s">.8.8</span><span class="p">;</span> <span class="c1"># use Google's public DNS nameserver</span>
</code></pre></div></div>
<p>If the nameserver returns multiple IP addresses for the host name, this method will pick up one randomly.</p>
<p>In case of error, the method returns <code class="language-plaintext highlighter-rouge">nil</code> followed by a string describing the error. In case of success, the method returns <code class="language-plaintext highlighter-rouge">1</code>.</p>
<p>Here is an example for connecting to a UDP (memcached) server:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/test</span> <span class="p">{</span>
<span class="kn">resolver</span> <span class="mf">8.8</span><span class="s">.8.8</span><span class="p">;</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">sock</span> <span class="p">=</span> <span class="s">ngx.socket.udp()</span>
<span class="s">local</span> <span class="s">ok,</span> <span class="s">err</span> <span class="p">=</span> <span class="s">sock:setpeername("my.memcached.server.domain",</span> <span class="mi">11211</span><span class="s">)</span>
<span class="s">if</span> <span class="s">not</span> <span class="s">ok</span> <span class="s">then</span>
<span class="s">ngx.say("failed</span> <span class="s">to</span> <span class="s">connect</span> <span class="s">to</span> <span class="s">memcached:</span> <span class="s">",</span> <span class="s">err)</span>
<span class="s">return</span>
<span class="s">end</span>
<span class="s">ngx.say("successfully</span> <span class="s">connected</span> <span class="s">to</span> <span class="s">memcached!")</span>
<span class="s">sock:close()</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Since the <code class="language-plaintext highlighter-rouge">v0.7.18</code> release, connecting to a datagram unix domain socket file is also possible on Linux:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">sock</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">socket</span><span class="p">.</span><span class="n">udp</span><span class="p">()</span>
<span class="kd">local</span> <span class="n">ok</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">sock</span><span class="p">:</span><span class="n">setpeername</span><span class="p">(</span><span class="s2">"unix:/tmp/some-datagram-service.sock"</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">ok</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"failed to connect to the datagram unix domain socket: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
</code></pre></div></div>
<p>assuming the datagram service is listening on the unix domain socket file <code class="language-plaintext highlighter-rouge">/tmp/some-datagram-service.sock</code> and the client socket will use the “autobind” feature on Linux.</p>
<p>Calling this method on an already connected socket object will cause the original connection to be closed first.</p>
<p>This method was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.7</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="udpsocksend">udpsock:send</h2>
<p><strong>syntax:</strong> <em>ok, err = udpsock:send(data)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>Sends data on the current UDP or datagram unix domain socket object.</p>
<p>In case of success, it returns <code class="language-plaintext highlighter-rouge">1</code>. Otherwise, it returns <code class="language-plaintext highlighter-rouge">nil</code> and a string describing the error.</p>
<p>The input argument <code class="language-plaintext highlighter-rouge">data</code> can either be a Lua string or a (nested) Lua table holding string fragments. In case of table arguments, this method will copy all the string elements piece by piece to the underlying Nginx socket send buffers, which is usually optimal than doing string concatenation operations on the Lua land.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.7</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="udpsockreceive">udpsock:receive</h2>
<p><strong>syntax:</strong> <em>data, err = udpsock:receive(size?)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>Receives data from the UDP or datagram unix domain socket object with an optional receive buffer size argument, <code class="language-plaintext highlighter-rouge">size</code>.</p>
<p>This method is a synchronous operation and is 100% nonblocking.</p>
<p>In case of success, it returns the data received; in case of error, it returns <code class="language-plaintext highlighter-rouge">nil</code> with a string describing the error.</p>
<p>If the <code class="language-plaintext highlighter-rouge">size</code> argument is specified, then this method will use this size as the receive buffer size. But when this size is greater than <code class="language-plaintext highlighter-rouge">8192</code>, then <code class="language-plaintext highlighter-rouge">8192</code> will be used instead.</p>
<p>If no argument is specified, then the maximal buffer size, <code class="language-plaintext highlighter-rouge">8192</code> is assumed.</p>
<p>Timeout for the reading operation is controlled by the <a href="#lua_socket_read_timeout">lua_socket_read_timeout</a> config directive and the <a href="#udpsocksettimeout">settimeout</a> method. And the latter takes priority. For example:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">sock</span><span class="p">:</span><span class="n">settimeout</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span> <span class="c1">-- one second timeout</span>
<span class="kd">local</span> <span class="n">data</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">sock</span><span class="p">:</span><span class="n">receive</span><span class="p">()</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">data</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"failed to read a packet: "</span><span class="p">,</span> <span class="n">data</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"successfully read a packet: "</span><span class="p">,</span> <span class="n">data</span><span class="p">)</span>
</code></pre></div></div>
<p>It is important here to call the <a href="#udpsocksettimeout">settimeout</a> method <em>before</em> calling this method.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.7</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="udpsockclose">udpsock:close</h2>
<p><strong>syntax:</strong> <em>ok, err = udpsock:close()</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>Closes the current UDP or datagram unix domain socket. It returns the <code class="language-plaintext highlighter-rouge">1</code> in case of success and returns <code class="language-plaintext highlighter-rouge">nil</code> with a string describing the error otherwise.</p>
<p>Socket objects that have not invoked this method (and associated connections) will be closed when the socket object is released by the Lua GC (Garbage Collector) or the current client HTTP request finishes processing.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.7</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="udpsocksettimeout">udpsock:settimeout</h2>
<p><strong>syntax:</strong> <em>udpsock:settimeout(time)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>Set the timeout value in milliseconds for subsequent socket operations (like <a href="#udpsockreceive">receive</a>).</p>
<p>Settings done by this method takes priority over those config directives, like <a href="#lua_socket_read_timeout">lua_socket_read_timeout</a>.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.7</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxsockettcp">ngx.socket.tcp</h2>
<p><strong>syntax:</strong> <em>tcpsock = ngx.socket.tcp()</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>Creates and returns a TCP or stream-oriented unix domain socket object (also known as one type of the “cosocket” objects). The following methods are supported on this object:</p>
<ul>
<li><a href="#tcpsockconnect">connect</a></li>
<li><a href="#tcpsocksslhandshake">sslhandshake</a></li>
<li><a href="#tcpsocksend">send</a></li>
<li><a href="#tcpsockreceive">receive</a></li>
<li><a href="#tcpsockclose">close</a></li>
<li><a href="#tcpsocksettimeout">settimeout</a></li>
<li><a href="#tcpsocksetoption">setoption</a></li>
<li><a href="#tcpsockreceiveuntil">receiveuntil</a></li>
<li><a href="#tcpsocksetkeepalive">setkeepalive</a></li>
<li><a href="#tcpsockgetreusedtimes">getreusedtimes</a></li>
</ul>
<p>It is intended to be compatible with the TCP API of the <a href="http://w3.impa.br/~diego/software/luasocket/tcp.html">LuaSocket</a> library but is 100% nonblocking out of the box. Also, we introduce some new APIs to provide more functionalities.</p>
<p>The cosocket object created by this API function has exactly the same lifetime as the Lua handler creating it. So never pass the cosocket object to any other Lua handler (including ngx.timer callback functions) and never share the cosocket object between different NGINX requests.</p>
<p>For every cosocket objects underlying connection, if you do not
explicitly close it (via <a href="#tcpsockclose">close</a>) or put it back to the connection
pool (via <a href="#tcpsocksetkeepalive">setkeepalive</a>), then it is automatically closed when one of
the following two events happens:</p>
<ul>
<li>the current request handler completes, or</li>
<li>the Lua cosocket object value gets collected by the Lua GC.</li>
</ul>
<p>Fatal errors in cosocket operations always automatically close the current
connection (note that, read timeout error is the only error that is
not fatal), and if you call <a href="#tcpsockclose">close</a> on a closed connection, you will get
the “closed” error.</p>
<p>Starting from the <code class="language-plaintext highlighter-rouge">0.9.9</code> release, the cosocket object here is full-duplex, that is, a reader “light thread” and a writer “light thread” can operate on a single cosocket object simultaneously (both “light threads” must belong to the same Lua handler though, see reasons above). But you cannot have two “light threads” both reading (or writing or connecting) the same cosocket, otherwise you might get an error like “socket busy reading” when calling the methods of the cosocket object.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc1</code> release.</p>
<p>See also <a href="#ngxsocketudp">ngx.socket.udp</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="tcpsockconnect">tcpsock:connect</h2>
<p><strong>syntax:</strong> <em>ok, err = tcpsock:connect(host, port, options_table?)</em></p>
<p><strong>syntax:</strong> <em>ok, err = tcpsock:connect(“unix:/path/to/unix-domain.socket”, options_table?)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>Attempts to connect a TCP socket object to a remote server or to a stream unix domain socket file without blocking.</p>
<p>Before actually resolving the host name and connecting to the remote backend, this method will always look up the connection pool for matched idle connections created by previous calls of this method (or the <a href="#ngxsocketconnect">ngx.socket.connect</a> function).</p>
<p>Both IP addresses and domain names can be specified as the <code class="language-plaintext highlighter-rouge">host</code> argument. In case of domain names, this method will use Nginx cores dynamic resolver to parse the domain name without blocking and it is required to configure the <a href="http://nginx.org/en/docs/http/ngx_http_core_module.html#resolver">resolver</a> directive in the <code class="language-plaintext highlighter-rouge">nginx.conf</code> file like this:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">resolver</span> <span class="mf">8.8</span><span class="s">.8.8</span><span class="p">;</span> <span class="c1"># use Google's public DNS nameserver</span>
</code></pre></div></div>
<p>If the nameserver returns multiple IP addresses for the host name, this method will pick up one randomly.</p>
<p>In case of error, the method returns <code class="language-plaintext highlighter-rouge">nil</code> followed by a string describing the error. In case of success, the method returns <code class="language-plaintext highlighter-rouge">1</code>.</p>
<p>Here is an example for connecting to a TCP server:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/test</span> <span class="p">{</span>
<span class="kn">resolver</span> <span class="mf">8.8</span><span class="s">.8.8</span><span class="p">;</span>
<span class="kn">content_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">sock</span> <span class="p">=</span> <span class="s">ngx.socket.tcp()</span>
<span class="s">local</span> <span class="s">ok,</span> <span class="s">err</span> <span class="p">=</span> <span class="s">sock:connect("www.google.com",</span> <span class="mi">80</span><span class="s">)</span>
<span class="s">if</span> <span class="s">not</span> <span class="s">ok</span> <span class="s">then</span>
<span class="s">ngx.say("failed</span> <span class="s">to</span> <span class="s">connect</span> <span class="s">to</span> <span class="s">google:</span> <span class="s">",</span> <span class="s">err)</span>
<span class="s">return</span>
<span class="s">end</span>
<span class="s">ngx.say("successfully</span> <span class="s">connected</span> <span class="s">to</span> <span class="s">google!")</span>
<span class="s">sock:close()</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>Connecting to a Unix Domain Socket file is also possible:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">sock</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">socket</span><span class="p">.</span><span class="n">tcp</span><span class="p">()</span>
<span class="kd">local</span> <span class="n">ok</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">sock</span><span class="p">:</span><span class="n">connect</span><span class="p">(</span><span class="s2">"unix:/tmp/memcached.sock"</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">ok</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"failed to connect to the memcached unix domain socket: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
</code></pre></div></div>
<p>assuming memcached (or something else) is listening on the unix domain socket file <code class="language-plaintext highlighter-rouge">/tmp/memcached.sock</code>.</p>
<p>Timeout for the connecting operation is controlled by the <a href="#lua_socket_connect_timeout">lua_socket_connect_timeout</a> config directive and the <a href="#tcpsocksettimeout">settimeout</a> method. And the latter takes priority. For example:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">sock</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">socket</span><span class="p">.</span><span class="n">tcp</span><span class="p">()</span>
<span class="n">sock</span><span class="p">:</span><span class="n">settimeout</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span> <span class="c1">-- one second timeout</span>
<span class="kd">local</span> <span class="n">ok</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">sock</span><span class="p">:</span><span class="n">connect</span><span class="p">(</span><span class="n">host</span><span class="p">,</span> <span class="n">port</span><span class="p">)</span>
</code></pre></div></div>
<p>It is important here to call the <a href="#tcpsocksettimeout">settimeout</a> method <em>before</em> calling this method.</p>
<p>Calling this method on an already connected socket object will cause the original connection to be closed first.</p>
<p>An optional Lua table can be specified as the last argument to this method to specify various connect options:</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">pool</code>
specify a custom name for the connection pool being used. If omitted, then the connection pool name will be generated from the string template <code class="language-plaintext highlighter-rouge">"&lt;host&gt;:&lt;port&gt;"</code> or <code class="language-plaintext highlighter-rouge">"&lt;unix-socket-path&gt;"</code>.</li>
</ul>
<p>The support for the options table argument was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.7</code> release.</p>
<p>This method was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc1</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="tcpsocksslhandshake">tcpsock:sslhandshake</h2>
<p><strong>syntax:</strong> <em>session, err = tcpsock:sslhandshake(reused_session?, server_name?, ssl_verify?)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>Does SSL/TLS handshake on the currently established connection.</p>
<p>The optional <code class="language-plaintext highlighter-rouge">reused_session</code> argument can take a former SSL
session userdata returned by a previous <code class="language-plaintext highlighter-rouge">sslhandshake</code>
call for exactly the same target. For short-lived connections, reusing SSL
sessions can usually speed up the handshake by one order by magnitude but it
is not so useful if the connection pool is enabled. This argument defaults to
<code class="language-plaintext highlighter-rouge">nil</code>. If this argument takes the boolean <code class="language-plaintext highlighter-rouge">false</code> value, no SSL session
userdata would return by this call and only a Lua boolean will be returned as
the first return value; otherwise the current SSL session will
always be returned as the first argument in case of successes.</p>
<p>The optional <code class="language-plaintext highlighter-rouge">server_name</code> argument is used to specify the server
name for the new TLS extension Server Name Indication (SNI). Use of SNI can
make different servers share the same IP address on the server side. Also,
when SSL verification is enabled, this <code class="language-plaintext highlighter-rouge">server_name</code> argument is
also used to validate the server name specified in the server certificate sent from
the remote.</p>
<p>The optional <code class="language-plaintext highlighter-rouge">ssl_verify</code> argument takes a Lua boolean value to
control whether to perform SSL verification. When set to <code class="language-plaintext highlighter-rouge">true</code>, the server
certificate will be verified according to the CA certificates specified by
the <a href="#lua_ssl_trusted_certificate">lua_ssl_trusted_certificate</a> directive.
You may also need to adjust the <a href="#lua_ssl_verify_depth">lua_ssl_verify_depth</a>
directive to control how deep we should follow along the certificate chain.
Also, when the <code class="language-plaintext highlighter-rouge">ssl_verify</code> argument is true and the
<code class="language-plaintext highlighter-rouge">server_name</code> argument is also specified, the latter will be used
to validate the server name in the server certificate.</p>
<p>For connections that have already done SSL/TLS handshake, this method returns
immediately.</p>
<p>This method was first introduced in the <code class="language-plaintext highlighter-rouge">v0.9.11</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="tcpsocksend">tcpsock:send</h2>
<p><strong>syntax:</strong> <em>bytes, err = tcpsock:send(data)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>Sends data without blocking on the current TCP or Unix Domain Socket connection.</p>
<p>This method is a synchronous operation that will not return until <em>all</em> the data has been flushed into the system socket send buffer or an error occurs.</p>
<p>In case of success, it returns the total number of bytes that have been sent. Otherwise, it returns <code class="language-plaintext highlighter-rouge">nil</code> and a string describing the error.</p>
<p>The input argument <code class="language-plaintext highlighter-rouge">data</code> can either be a Lua string or a (nested) Lua table holding string fragments. In case of table arguments, this method will copy all the string elements piece by piece to the underlying Nginx socket send buffers, which is usually optimal than doing string concatenation operations on the Lua land.</p>
<p>Timeout for the sending operation is controlled by the <a href="#lua_socket_send_timeout">lua_socket_send_timeout</a> config directive and the <a href="#tcpsocksettimeout">settimeout</a> method. And the latter takes priority. For example:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">sock</span><span class="p">:</span><span class="n">settimeout</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span> <span class="c1">-- one second timeout</span>
<span class="kd">local</span> <span class="n">bytes</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">sock</span><span class="p">:</span><span class="n">send</span><span class="p">(</span><span class="n">request</span><span class="p">)</span>
</code></pre></div></div>
<p>It is important here to call the <a href="#tcpsocksettimeout">settimeout</a> method <em>before</em> calling this method.</p>
<p>In case of any connection errors, this method always automatically closes the current connection.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc1</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="tcpsockreceive">tcpsock:receive</h2>
<p><strong>syntax:</strong> <em>data, err, partial = tcpsock:receive(size)</em></p>
<p><strong>syntax:</strong> <em>data, err, partial = tcpsock:receive(pattern?)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>Receives data from the connected socket according to the reading pattern or size.</p>
<p>This method is a synchronous operation just like the <a href="#tcpsocksend">send</a> method and is 100% nonblocking.</p>
<p>In case of success, it returns the data received; in case of error, it returns <code class="language-plaintext highlighter-rouge">nil</code> with a string describing the error and the partial data received so far.</p>
<p>If a number-like argument is specified (including strings that look like numbers), then it is interpreted as a size. This method will not return until it reads exactly this size of data or an error occurs.</p>
<p>If a non-number-like string argument is specified, then it is interpreted as a “pattern”. The following patterns are supported:</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">'*a'</code>: reads from the socket until the connection is closed. No end-of-line translation is performed;</li>
<li><code class="language-plaintext highlighter-rouge">'*l'</code>: reads a line of text from the socket. The line is terminated by a <code class="language-plaintext highlighter-rouge">Line Feed</code> (LF) character (ASCII 10), optionally preceded by a <code class="language-plaintext highlighter-rouge">Carriage Return</code> (CR) character (ASCII 13). The CR and LF characters are not included in the returned line. In fact, all CR characters are ignored by the pattern.</li>
</ul>
<p>If no argument is specified, then it is assumed to be the pattern <code class="language-plaintext highlighter-rouge">'*l'</code>, that is, the line reading pattern.</p>
<p>Timeout for the reading operation is controlled by the <a href="#lua_socket_read_timeout">lua_socket_read_timeout</a> config directive and the <a href="#tcpsocksettimeout">settimeout</a> method. And the latter takes priority. For example:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="n">sock</span><span class="p">:</span><span class="n">settimeout</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span> <span class="c1">-- one second timeout</span>
<span class="kd">local</span> <span class="n">line</span><span class="p">,</span> <span class="n">err</span><span class="p">,</span> <span class="n">partial</span> <span class="o">=</span> <span class="n">sock</span><span class="p">:</span><span class="n">receive</span><span class="p">()</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">line</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"failed to read a line: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"successfully read a line: "</span><span class="p">,</span> <span class="n">line</span><span class="p">)</span>
</code></pre></div></div>
<p>It is important here to call the <a href="#tcpsocksettimeout">settimeout</a> method <em>before</em> calling this method.</p>
<p>Since the <code class="language-plaintext highlighter-rouge">v0.8.8</code> release, this method no longer automatically closes the current connection when the read timeout error happens. For other connection errors, this method always automatically closes the connection.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc1</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="tcpsockreceiveuntil">tcpsock:receiveuntil</h2>
<p><strong>syntax:</strong> <em>iterator = tcpsock:receiveuntil(pattern, options?)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>This method returns an iterator Lua function that can be called to read the data stream until it sees the specified pattern or an error occurs.</p>
<p>Here is an example for using this method to read a data stream with the boundary sequence <code class="language-plaintext highlighter-rouge">--abcedhb</code>:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">reader</span> <span class="o">=</span> <span class="n">sock</span><span class="p">:</span><span class="n">receiveuntil</span><span class="p">(</span><span class="s2">"</span><span class="se">\r\n</span><span class="s2">--abcedhb"</span><span class="p">)</span>
<span class="kd">local</span> <span class="n">data</span><span class="p">,</span> <span class="n">err</span><span class="p">,</span> <span class="n">partial</span> <span class="o">=</span> <span class="n">reader</span><span class="p">()</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">data</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"failed to read the data stream: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">end</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"read the data stream: "</span><span class="p">,</span> <span class="n">data</span><span class="p">)</span>
</code></pre></div></div>
<p>When called without any argument, the iterator function returns the received data right <em>before</em> the specified pattern string in the incoming data stream. So for the example above, if the incoming data stream is <code class="language-plaintext highlighter-rouge">'hello, world! -agentzh\r\n--abcedhb blah blah'</code>, then the string <code class="language-plaintext highlighter-rouge">'hello, world! -agentzh'</code> will be returned.</p>
<p>In case of error, the iterator function will return <code class="language-plaintext highlighter-rouge">nil</code> along with a string describing the error and the partial data bytes that have been read so far.</p>
<p>The iterator function can be called multiple times and can be mixed safely with other cosocket method calls or other iterator function calls.</p>
<p>The iterator function behaves differently (i.e., like a real iterator) when it is called with a <code class="language-plaintext highlighter-rouge">size</code> argument. That is, it will read that <code class="language-plaintext highlighter-rouge">size</code> of data on each invocation and will return <code class="language-plaintext highlighter-rouge">nil</code> at the last invocation (either sees the boundary pattern or meets an error). For the last successful invocation of the iterator function, the <code class="language-plaintext highlighter-rouge">err</code> return value will be <code class="language-plaintext highlighter-rouge">nil</code> too. The iterator function will be reset after the last successful invocation that returns <code class="language-plaintext highlighter-rouge">nil</code> data and <code class="language-plaintext highlighter-rouge">nil</code> error. Consider the following example:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">reader</span> <span class="o">=</span> <span class="n">sock</span><span class="p">:</span><span class="n">receiveuntil</span><span class="p">(</span><span class="s2">"</span><span class="se">\r\n</span><span class="s2">--abcedhb"</span><span class="p">)</span>
<span class="k">while</span> <span class="kc">true</span> <span class="k">do</span>
<span class="kd">local</span> <span class="n">data</span><span class="p">,</span> <span class="n">err</span><span class="p">,</span> <span class="n">partial</span> <span class="o">=</span> <span class="n">reader</span><span class="p">(</span><span class="mi">4</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">data</span> <span class="k">then</span>
<span class="k">if</span> <span class="n">err</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"failed to read the data stream: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">break</span>
<span class="k">end</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"read done"</span><span class="p">)</span>
<span class="k">break</span>
<span class="k">end</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"read chunk: ["</span><span class="p">,</span> <span class="n">data</span><span class="p">,</span> <span class="s2">"]"</span><span class="p">)</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Then for the incoming data stream <code class="language-plaintext highlighter-rouge">'hello, world! -agentzh\r\n--abcedhb blah blah'</code>, we shall get the following output from the sample code above:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>read chunk: [hell]
read chunk: [o, w]
read chunk: [orld]
read chunk: [! -a]
read chunk: [gent]
read chunk: [zh]
read done
</code></pre></div></div>
<p>Note that, the actual data returned <em>might</em> be a little longer than the size limit specified by the <code class="language-plaintext highlighter-rouge">size</code> argument when the boundary pattern has ambiguity for streaming parsing. Near the boundary of the data stream, the data string actually returned could also be shorter than the size limit.</p>
<p>Timeout for the iterator functions reading operation is controlled by the <a href="#lua_socket_read_timeout">lua_socket_read_timeout</a> config directive and the <a href="#tcpsocksettimeout">settimeout</a> method. And the latter takes priority. For example:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">readline</span> <span class="o">=</span> <span class="n">sock</span><span class="p">:</span><span class="n">receiveuntil</span><span class="p">(</span><span class="s2">"</span><span class="se">\r\n</span><span class="s2">"</span><span class="p">)</span>
<span class="n">sock</span><span class="p">:</span><span class="n">settimeout</span><span class="p">(</span><span class="mi">1000</span><span class="p">)</span> <span class="c1">-- one second timeout</span>
<span class="n">line</span><span class="p">,</span> <span class="n">err</span><span class="p">,</span> <span class="n">partial</span> <span class="o">=</span> <span class="n">readline</span><span class="p">()</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">line</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"failed to read a line: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"successfully read a line: "</span><span class="p">,</span> <span class="n">line</span><span class="p">)</span>
</code></pre></div></div>
<p>It is important here to call the <a href="#tcpsocksettimeout">settimeout</a> method <em>before</em> calling the iterator function (note that the <code class="language-plaintext highlighter-rouge">receiveuntil</code> call is irrelevant here).</p>
<p>As from the <code class="language-plaintext highlighter-rouge">v0.5.1</code> release, this method also takes an optional <code class="language-plaintext highlighter-rouge">options</code> table argument to control the behavior. The following options are supported:</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">inclusive</code></li>
</ul>
<p>The <code class="language-plaintext highlighter-rouge">inclusive</code> takes a boolean value to control whether to include the pattern string in the returned data string. Default to <code class="language-plaintext highlighter-rouge">false</code>. For example,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">reader</span> <span class="o">=</span> <span class="n">tcpsock</span><span class="p">:</span><span class="n">receiveuntil</span><span class="p">(</span><span class="s2">"_END_"</span><span class="p">,</span> <span class="p">{</span> <span class="n">inclusive</span> <span class="o">=</span> <span class="kc">true</span> <span class="p">})</span>
<span class="kd">local</span> <span class="n">data</span> <span class="o">=</span> <span class="n">reader</span><span class="p">()</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
</code></pre></div></div>
<p>Then for the input data stream <code class="language-plaintext highlighter-rouge">"hello world _END_ blah blah blah"</code>, then the example above will output <code class="language-plaintext highlighter-rouge">hello world _END_</code>, including the pattern string <code class="language-plaintext highlighter-rouge">_END_</code> itself.</p>
<p>Since the <code class="language-plaintext highlighter-rouge">v0.8.8</code> release, this method no longer automatically closes the current connection when the read timeout error happens. For other connection errors, this method always automatically closes the connection.</p>
<p>This method was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc1</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="tcpsockclose">tcpsock:close</h2>
<p><strong>syntax:</strong> <em>ok, err = tcpsock:close()</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>Closes the current TCP or stream unix domain socket. It returns the <code class="language-plaintext highlighter-rouge">1</code> in case of success and returns <code class="language-plaintext highlighter-rouge">nil</code> with a string describing the error otherwise.</p>
<p>Note that there is no need to call this method on socket objects that have invoked the <a href="#tcpsocksetkeepalive">setkeepalive</a> method because the socket object is already closed (and the current connection is saved into the built-in connection pool).</p>
<p>Socket objects that have not invoked this method (and associated connections) will be closed when the socket object is released by the Lua GC (Garbage Collector) or the current client HTTP request finishes processing.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc1</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="tcpsocksettimeout">tcpsock:settimeout</h2>
<p><strong>syntax:</strong> <em>tcpsock:settimeout(time)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>Set the timeout value in milliseconds for subsequent socket operations (<a href="#tcpsockconnect">connect</a>, <a href="#tcpsockreceive">receive</a>, and iterators returned from <a href="#tcpsockreceiveuntil">receiveuntil</a>).</p>
<p>Settings done by this method takes priority over those config directives, i.e., <a href="#lua_socket_connect_timeout">lua_socket_connect_timeout</a>, <a href="#lua_socket_send_timeout">lua_socket_send_timeout</a>, and <a href="#lua_socket_read_timeout">lua_socket_read_timeout</a>.</p>
<p>Note that this method does <em>not</em> affect the <a href="#lua_socket_keepalive_timeout">lua_socket_keepalive_timeout</a> setting; the <code class="language-plaintext highlighter-rouge">timeout</code> argument to the <a href="#tcpsocksetkeepalive">setkeepalive</a> method should be used for this purpose instead.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc1</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="tcpsocksetoption">tcpsock:setoption</h2>
<p><strong>syntax:</strong> <em>tcpsock:setoption(option, value?)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>This function is added for <a href="http://w3.impa.br/~diego/software/luasocket/tcp.html">LuaSocket</a> API compatibility and does nothing for now. Its functionality will be implemented in future.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc1</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="tcpsocksetkeepalive">tcpsock:setkeepalive</h2>
<p><strong>syntax:</strong> <em>ok, err = tcpsock:setkeepalive(timeout?, size?)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>Puts the current sockets connection immediately into the cosocket built-in connection pool and keep it alive until other <a href="#tcpsockconnect">connect</a> method calls request it or the associated maximal idle timeout is expired.</p>
<p>The first optional argument, <code class="language-plaintext highlighter-rouge">timeout</code>, can be used to specify the maximal idle timeout (in milliseconds) for the current connection. If omitted, the default setting in the <a href="#lua_socket_keepalive_timeout">lua_socket_keepalive_timeout</a> config directive will be used. If the <code class="language-plaintext highlighter-rouge">0</code> value is given, then the timeout interval is unlimited.</p>
<p>The second optional argument, <code class="language-plaintext highlighter-rouge">size</code>, can be used to specify the maximal number of connections allowed in the connection pool for the current server (i.e., the current host-port pair or the unix domain socket file path). Note that the size of the connection pool cannot be changed once the pool is created. When this argument is omitted, the default setting in the <a href="#lua_socket_pool_size">lua_socket_pool_size</a> config directive will be used.</p>
<p>When the connection pool exceeds the available size limit, the least recently used (idle) connection already in the pool will be closed to make room for the current connection.</p>
<p>Note that the cosocket connection pool is per Nginx worker process rather than per Nginx server instance, so the size limit specified here also applies to every single Nginx worker process.</p>
<p>Idle connections in the pool will be monitored for any exceptional events like connection abortion or unexpected incoming data on the line, in which cases the connection in question will be closed and removed from the pool.</p>
<p>In case of success, this method returns <code class="language-plaintext highlighter-rouge">1</code>; otherwise, it returns <code class="language-plaintext highlighter-rouge">nil</code> and a string describing the error.</p>
<p>When the system receive buffer for the current connection has unread data, then this method will return the “connection in dubious state” error message (as the second return value) because the previous session has unread data left behind for the next session and the connection is not safe to be reused.</p>
<p>This method also makes the current cosocket object enter the “closed” state, so there is no need to manually call the <a href="#tcpsockclose">close</a> method on it afterwards.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc1</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="tcpsockgetreusedtimes">tcpsock:getreusedtimes</h2>
<p><strong>syntax:</strong> <em>count, err = tcpsock:getreusedtimes()</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>This method returns the (successfully) reused times for the current connection. In case of error, it returns <code class="language-plaintext highlighter-rouge">nil</code> and a string describing the error.</p>
<p>If the current connection does not come from the built-in connection pool, then this method always returns <code class="language-plaintext highlighter-rouge">0</code>, that is, the connection has never been reused (yet). If the connection comes from the connection pool, then the return value is always non-zero. So this method can also be used to determine if the current connection comes from the pool.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc1</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxsocketconnect">ngx.socket.connect</h2>
<p><strong>syntax:</strong> <em>tcpsock, err = ngx.socket.connect(host, port)</em></p>
<p><strong>syntax:</strong> <em>tcpsock, err = ngx.socket.connect(“unix:/path/to/unix-domain.socket”)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>This function is a shortcut for combining <a href="#ngxsockettcp">ngx.socket.tcp()</a> and the <a href="#tcpsockconnect">connect()</a> method call in a single operation. It is actually implemented like this:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">sock</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">socket</span><span class="p">.</span><span class="n">tcp</span><span class="p">()</span>
<span class="kd">local</span> <span class="n">ok</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">sock</span><span class="p">:</span><span class="n">connect</span><span class="p">(</span><span class="o">...</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">ok</span> <span class="k">then</span>
<span class="k">return</span> <span class="kc">nil</span><span class="p">,</span> <span class="n">err</span>
<span class="k">end</span>
<span class="k">return</span> <span class="n">sock</span>
</code></pre></div></div>
<p>There is no way to use the <a href="#tcpsocksettimeout">settimeout</a> method to specify connecting timeout for this method and the <a href="#lua_socket_connect_timeout">lua_socket_connect_timeout</a> directive must be set at configure time instead.</p>
<p>This feature was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.0rc1</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxget_phase">ngx.get_phase</h2>
<p><strong>syntax:</strong> <em>str = ngx.get_phase()</em></p>
<p><strong>context:</strong> <em>init_by_lua</em>, init_worker_by_lua<em>, set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.**</p>
<p>Retrieves the current running phase name. Possible return values are</p>
<ul>
<li><code class="language-plaintext highlighter-rouge">init</code>
for the context of <a href="#init_by_lua">init_by_lua</a> or <a href="#init_by_lua_file">init_by_lua_file</a>.</li>
<li><code class="language-plaintext highlighter-rouge">init_worker</code>
for the context of <a href="#init_worker_by_lua">init_worker_by_lua</a> or <a href="#init_worker_by_lua_file">init_worker_by_lua_file</a>.</li>
<li><code class="language-plaintext highlighter-rouge">set</code>
for the context of <a href="#set_by_lua">set_by_lua</a> or <a href="#set_by_lua_file">set_by_lua_file</a>.</li>
<li><code class="language-plaintext highlighter-rouge">rewrite</code>
for the context of <a href="#rewrite_by_lua">rewrite_by_lua</a> or <a href="#rewrite_by_lua_file">rewrite_by_lua_file</a>.</li>
<li><code class="language-plaintext highlighter-rouge">access</code>
for the context of <a href="#access_by_lua">access_by_lua</a> or <a href="#access_by_lua_file">access_by_lua_file</a>.</li>
<li><code class="language-plaintext highlighter-rouge">content</code>
for the context of <a href="#content_by_lua">content_by_lua</a> or <a href="#content_by_lua_file">content_by_lua_file</a>.</li>
<li><code class="language-plaintext highlighter-rouge">header_filter</code>
for the context of <a href="#header_filter_by_lua">header_filter_by_lua</a> or <a href="#header_filter_by_lua_file">header_filter_by_lua_file</a>.</li>
<li><code class="language-plaintext highlighter-rouge">body_filter</code>
for the context of <a href="#body_filter_by_lua">body_filter_by_lua</a> or <a href="#body_filter_by_lua_file">body_filter_by_lua_file</a>.</li>
<li><code class="language-plaintext highlighter-rouge">log</code>
for the context of <a href="#log_by_lua">log_by_lua</a> or <a href="#log_by_lua_file">log_by_lua_file</a>.</li>
<li><code class="language-plaintext highlighter-rouge">timer</code>
for the context of user callback functions for <a href="#ngxtimerat">ngx.timer.*</a>.</li>
</ul>
<p>This API was first introduced in the <code class="language-plaintext highlighter-rouge">v0.5.10</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxthreadspawn">ngx.thread.spawn</h2>
<p><strong>syntax:</strong> <em>co = ngx.thread.spawn(func, arg1, arg2, …)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>Spawns a new user “light thread” with the Lua function <code class="language-plaintext highlighter-rouge">func</code> as well as those optional arguments <code class="language-plaintext highlighter-rouge">arg1</code>, <code class="language-plaintext highlighter-rouge">arg2</code>, and etc. Returns a Lua thread (or Lua coroutine) object represents this “light thread”.</p>
<p>“Light threads” are just a special kind of Lua coroutines that are scheduled by the ngx_lua module.</p>
<p>Before <code class="language-plaintext highlighter-rouge">ngx.thread.spawn</code> returns, the <code class="language-plaintext highlighter-rouge">func</code> will be called with those optional arguments until it returns, aborts with an error, or gets yielded due to I/O operations via the <a href="#nginx-api-for-lua">Nginx API for Lua</a> (like <a href="#tcpsockreceive">tcpsock:receive</a>).</p>
<p>After <code class="language-plaintext highlighter-rouge">ngx.thread.spawn</code> returns, the newly-created “light thread” will keep running asynchronously usually at various I/O events.</p>
<p>All the Lua code chunks running by <a href="#rewrite_by_lua">rewrite_by_lua</a>, <a href="#access_by_lua">access_by_lua</a>, and <a href="#content_by_lua">content_by_lua</a> are in a boilerplate “light thread” created automatically by ngx_lua. Such boilerplate “light thread” are also called “entry threads”.</p>
<p>By default, the corresponding Nginx handler (e.g., <a href="#rewrite_by_lua">rewrite_by_lua</a> handler) will not terminate until</p>
<ol>
<li>both the “entry thread” and all the user “light threads” terminates,</li>
<li>a “light thread” (either the “entry thread” or a user “light thread” aborts by calling <a href="#ngxexit">ngx.exit</a>, <a href="#ngxexec">ngx.exec</a>, <a href="#ngxredirect">ngx.redirect</a>, or <a href="#ngxreqset_uri">ngx.req.set_uri(uri, true)</a>, or</li>
<li>the “entry thread” terminates with a Lua error.</li>
</ol>
<p>When the user “light thread” terminates with a Lua error, however, it will not abort other running “light threads” like the “entry thread” does.</p>
<p>Due to the limitation in the Nginx subrequest model, it is not allowed to abort a running Nginx subrequest in general. So it is also prohibited to abort a running “light thread” that is pending on one ore more Nginx subrequests. You must call <a href="#ngxthreadwait">ngx.thread.wait</a> to wait for those “light thread” to terminate before quitting the “world”. A notable exception here is that you can abort pending subrequests by calling <a href="#ngxexit">ngx.exit</a> with and only with the status code <code class="language-plaintext highlighter-rouge">ngx.ERROR</code> (-1), <code class="language-plaintext highlighter-rouge">408</code>, <code class="language-plaintext highlighter-rouge">444</code>, or <code class="language-plaintext highlighter-rouge">499</code>.</p>
<p>The “light threads” are not scheduled in a pre-emptive way. In other words, no time-slicing is performed automatically. A “light thread” will keep running exclusively on the CPU until</p>
<ol>
<li>a (nonblocking) I/O operation cannot be completed in a single run,</li>
<li>it calls <a href="#coroutineyield">coroutine.yield</a> to actively give up execution, or</li>
<li>it is aborted by a Lua error or an invocation of <a href="#ngxexit">ngx.exit</a>, <a href="#ngxexec">ngx.exec</a>, <a href="#ngxredirect">ngx.redirect</a>, or <a href="#ngxreqset_uri">ngx.req.set_uri(uri, true)</a>.</li>
</ol>
<p>For the first two cases, the “light thread” will usually be resumed later by the ngx_lua scheduler unless a “stop-the-world” event happens.</p>
<p>User “light threads” can create “light threads” themselves. And normal user coroutines created by <a href="#coroutinecreate">coroutine.create</a> can also create “light threads”. The coroutine (be it a normal Lua coroutine or a “light thread”) that directly spawns the “light thread” is called the “parent coroutine” for the “light thread” newly spawned.</p>
<p>The “parent coroutine” can call <a href="#ngxthreadwait">ngx.thread.wait</a> to wait on the termination of its child “light thread”.</p>
<p>You can call coroutine.status() and coroutine.yield() on the “light thread” coroutines.</p>
<p>The status of the “light thread” coroutine can be “zombie” if</p>
<ol>
<li>the current “light thread” already terminates (either successfully or with an error),</li>
<li>its parent coroutine is still alive, and</li>
<li>its parent coroutine is not waiting on it with <a href="#ngxthreadwait">ngx.thread.wait</a>.</li>
</ol>
<p>The following example demonstrates the use of coroutine.yield() in the “light thread” coroutines
to do manual time-slicing:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">yield</span> <span class="o">=</span> <span class="nb">coroutine.yield</span>
<span class="k">function</span> <span class="nf">f</span><span class="p">()</span>
<span class="kd">local</span> <span class="n">self</span> <span class="o">=</span> <span class="nb">coroutine.running</span><span class="p">()</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"f 1"</span><span class="p">)</span>
<span class="n">yield</span><span class="p">(</span><span class="n">self</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"f 2"</span><span class="p">)</span>
<span class="n">yield</span><span class="p">(</span><span class="n">self</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"f 3"</span><span class="p">)</span>
<span class="k">end</span>
<span class="kd">local</span> <span class="n">self</span> <span class="o">=</span> <span class="nb">coroutine.running</span><span class="p">()</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"0"</span><span class="p">)</span>
<span class="n">yield</span><span class="p">(</span><span class="n">self</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"1"</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">thread</span><span class="p">.</span><span class="n">spawn</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"2"</span><span class="p">)</span>
<span class="n">yield</span><span class="p">(</span><span class="n">self</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"3"</span><span class="p">)</span>
<span class="n">yield</span><span class="p">(</span><span class="n">self</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"4"</span><span class="p">)</span>
</code></pre></div></div>
<p>Then it will generate the output</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>0
1
f 1
2
f 2
3
f 3
4
</code></pre></div></div>
<p>“Light threads” are mostly useful for doing concurrent upstream requests in a single Nginx request handler, kinda like a generalized version of <a href="#ngxlocationcapture_multi">ngx.location.capture_multi</a> that can work with all the <a href="#nginx-api-for-lua">Nginx API for Lua</a>. The following example demonstrates parallel requests to MySQL, Memcached, and upstream HTTP services in a single Lua handler, and outputting the results in the order that they actually return (very much like the Facebook BigPipe model):</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="c1">-- query mysql, memcached, and a remote http service at the same time,</span>
<span class="c1">-- output the results in the order that they</span>
<span class="c1">-- actually return the results.</span>
<span class="kd">local</span> <span class="n">mysql</span> <span class="o">=</span> <span class="nb">require</span> <span class="s2">"resty.mysql"</span>
<span class="kd">local</span> <span class="n">memcached</span> <span class="o">=</span> <span class="nb">require</span> <span class="s2">"resty.memcached"</span>
<span class="kd">local</span> <span class="k">function</span> <span class="nf">query_mysql</span><span class="p">()</span>
<span class="kd">local</span> <span class="n">db</span> <span class="o">=</span> <span class="n">mysql</span><span class="p">:</span><span class="n">new</span><span class="p">()</span>
<span class="n">db</span><span class="p">:</span><span class="n">connect</span><span class="p">{</span>
<span class="n">host</span> <span class="o">=</span> <span class="s2">"127.0.0.1"</span><span class="p">,</span>
<span class="n">port</span> <span class="o">=</span> <span class="mi">3306</span><span class="p">,</span>
<span class="n">database</span> <span class="o">=</span> <span class="s2">"test"</span><span class="p">,</span>
<span class="n">user</span> <span class="o">=</span> <span class="s2">"monty"</span><span class="p">,</span>
<span class="n">password</span> <span class="o">=</span> <span class="s2">"mypass"</span>
<span class="p">}</span>
<span class="kd">local</span> <span class="n">res</span><span class="p">,</span> <span class="n">err</span><span class="p">,</span> <span class="n">errno</span><span class="p">,</span> <span class="n">sqlstate</span> <span class="o">=</span>
<span class="n">db</span><span class="p">:</span><span class="n">query</span><span class="p">(</span><span class="s2">"select * from cats order by id asc"</span><span class="p">)</span>
<span class="n">db</span><span class="p">:</span><span class="n">set_keepalive</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">100</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"mysql done: "</span><span class="p">,</span> <span class="n">cjson</span><span class="p">.</span><span class="n">encode</span><span class="p">(</span><span class="n">res</span><span class="p">))</span>
<span class="k">end</span>
<span class="kd">local</span> <span class="k">function</span> <span class="nf">query_memcached</span><span class="p">()</span>
<span class="kd">local</span> <span class="n">memc</span> <span class="o">=</span> <span class="n">memcached</span><span class="p">:</span><span class="n">new</span><span class="p">()</span>
<span class="n">memc</span><span class="p">:</span><span class="n">connect</span><span class="p">(</span><span class="s2">"127.0.0.1"</span><span class="p">,</span> <span class="mi">11211</span><span class="p">)</span>
<span class="kd">local</span> <span class="n">res</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">memc</span><span class="p">:</span><span class="n">get</span><span class="p">(</span><span class="s2">"some_key"</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"memcached done: "</span><span class="p">,</span> <span class="n">res</span><span class="p">)</span>
<span class="k">end</span>
<span class="kd">local</span> <span class="k">function</span> <span class="nf">query_http</span><span class="p">()</span>
<span class="kd">local</span> <span class="n">res</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">location</span><span class="p">.</span><span class="n">capture</span><span class="p">(</span><span class="s2">"/my-http-proxy"</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"http done: "</span><span class="p">,</span> <span class="n">res</span><span class="p">.</span><span class="n">body</span><span class="p">)</span>
<span class="k">end</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">thread</span><span class="p">.</span><span class="n">spawn</span><span class="p">(</span><span class="n">query_mysql</span><span class="p">)</span> <span class="c1">-- create thread 1</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">thread</span><span class="p">.</span><span class="n">spawn</span><span class="p">(</span><span class="n">query_memcached</span><span class="p">)</span> <span class="c1">-- create thread 2</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">thread</span><span class="p">.</span><span class="n">spawn</span><span class="p">(</span><span class="n">query_http</span><span class="p">)</span> <span class="c1">-- create thread 3</span>
</code></pre></div></div>
<p>This API was first enabled in the <code class="language-plaintext highlighter-rouge">v0.7.0</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxthreadwait">ngx.thread.wait</h2>
<p><strong>syntax:</strong> <em>ok, res1, res2, … = ngx.thread.wait(thread1, thread2, …)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>Waits on one or more child “light threads” and returns the results of the first “light thread” that terminates (either successfully or with an error).</p>
<p>The arguments <code class="language-plaintext highlighter-rouge">thread1</code>, <code class="language-plaintext highlighter-rouge">thread2</code>, and etc are the Lua thread objects returned by earlier calls of <a href="#ngxthreadspawn">ngx.thread.spawn</a>.</p>
<p>The return values have exactly the same meaning as <a href="#coroutineresume">coroutine.resume</a>, that is, the first value returned is a boolean value indicating whether the “light thread” terminates successfully or not, and subsequent values returned are the return values of the user Lua function that was used to spawn the “light thread” (in case of success) or the error object (in case of failure).</p>
<p>Only the direct “parent coroutine” can wait on its child “light thread”, otherwise a Lua exception will be raised.</p>
<p>The following example demonstrates the use of <code class="language-plaintext highlighter-rouge">ngx.thread.wait</code> and <a href="#ngxlocationcapture">ngx.location.capture</a> to emulate <a href="#ngxlocationcapture_multi">ngx.location.capture_multi</a>:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">capture</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">location</span><span class="p">.</span><span class="n">capture</span>
<span class="kd">local</span> <span class="n">spawn</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">thread</span><span class="p">.</span><span class="n">spawn</span>
<span class="kd">local</span> <span class="n">wait</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">thread</span><span class="p">.</span><span class="n">wait</span>
<span class="kd">local</span> <span class="n">say</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">say</span>
<span class="kd">local</span> <span class="k">function</span> <span class="nf">fetch</span><span class="p">(</span><span class="n">uri</span><span class="p">)</span>
<span class="k">return</span> <span class="n">capture</span><span class="p">(</span><span class="n">uri</span><span class="p">)</span>
<span class="k">end</span>
<span class="kd">local</span> <span class="n">threads</span> <span class="o">=</span> <span class="p">{</span>
<span class="n">spawn</span><span class="p">(</span><span class="n">fetch</span><span class="p">,</span> <span class="s2">"/foo"</span><span class="p">),</span>
<span class="n">spawn</span><span class="p">(</span><span class="n">fetch</span><span class="p">,</span> <span class="s2">"/bar"</span><span class="p">),</span>
<span class="n">spawn</span><span class="p">(</span><span class="n">fetch</span><span class="p">,</span> <span class="s2">"/baz"</span><span class="p">)</span>
<span class="p">}</span>
<span class="k">for</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span> <span class="o">#</span><span class="n">threads</span> <span class="k">do</span>
<span class="kd">local</span> <span class="n">ok</span><span class="p">,</span> <span class="n">res</span> <span class="o">=</span> <span class="n">wait</span><span class="p">(</span><span class="n">threads</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">ok</span> <span class="k">then</span>
<span class="n">say</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="s2">": failed to run: "</span><span class="p">,</span> <span class="n">res</span><span class="p">)</span>
<span class="k">else</span>
<span class="n">say</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="s2">": status: "</span><span class="p">,</span> <span class="n">res</span><span class="p">.</span><span class="n">status</span><span class="p">)</span>
<span class="n">say</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="s2">": body: "</span><span class="p">,</span> <span class="n">res</span><span class="p">.</span><span class="n">body</span><span class="p">)</span>
<span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Here it essentially implements the “wait all” model.</p>
<p>And below is an example demonstrating the “wait any” model:</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">function</span> <span class="nf">f</span><span class="p">()</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">0</span><span class="p">.</span><span class="mi">2</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"f: hello"</span><span class="p">)</span>
<span class="k">return</span> <span class="s2">"f done"</span>
<span class="k">end</span>
<span class="k">function</span> <span class="nf">g</span><span class="p">()</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">sleep</span><span class="p">(</span><span class="mi">0</span><span class="p">.</span><span class="mi">1</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"g: hello"</span><span class="p">)</span>
<span class="k">return</span> <span class="s2">"g done"</span>
<span class="k">end</span>
<span class="kd">local</span> <span class="n">tf</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">thread</span><span class="p">.</span><span class="n">spawn</span><span class="p">(</span><span class="n">f</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">tf</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"failed to spawn thread f: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"f thread created: "</span><span class="p">,</span> <span class="nb">coroutine.status</span><span class="p">(</span><span class="n">tf</span><span class="p">))</span>
<span class="kd">local</span> <span class="n">tg</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">thread</span><span class="p">.</span><span class="n">spawn</span><span class="p">(</span><span class="n">g</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">tg</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"failed to spawn thread g: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"g thread created: "</span><span class="p">,</span> <span class="nb">coroutine.status</span><span class="p">(</span><span class="n">tg</span><span class="p">))</span>
<span class="n">ok</span><span class="p">,</span> <span class="n">res</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">thread</span><span class="p">.</span><span class="n">wait</span><span class="p">(</span><span class="n">tf</span><span class="p">,</span> <span class="n">tg</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">ok</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"failed to wait: "</span><span class="p">,</span> <span class="n">res</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">say</span><span class="p">(</span><span class="s2">"res: "</span><span class="p">,</span> <span class="n">res</span><span class="p">)</span>
<span class="c1">-- stop the "world", aborting other running threads</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">exit</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">OK</span><span class="p">)</span>
</code></pre></div></div>
<p>And it will generate the following output:</p>
<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>f thread created: running
g thread created: running
g: hello
res: g done
</code></pre></div></div>
<p>This API was first enabled in the <code class="language-plaintext highlighter-rouge">v0.7.0</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxthreadkill">ngx.thread.kill</h2>
<p><strong>syntax:</strong> <em>ok, err = ngx.thread.kill(thread)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, ngx.timer.**</p>
<p>Kills a running “light thread” created by <a href="#ngxthreadspawn">ngx.thread.spawn</a>. Returns a true value when successful or <code class="language-plaintext highlighter-rouge">nil</code> and a string describing the error otherwise.</p>
<p>According to the current implementation, only the parent coroutine (or “light thread”) can kill a thread. Also, a running “light thread” with pending NGINX subrequests (initiated by <a href="#ngxlocationcapture">ngx.location.capture</a> for example) cannot be killed due to a limitation in the NGINX core.</p>
<p>This API was first enabled in the <code class="language-plaintext highlighter-rouge">v0.9.9</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxon_abort">ngx.on_abort</h2>
<p><strong>syntax:</strong> <em>ok, err = ngx.on_abort(callback)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua*, content_by_lua**</p>
<p>Registers a user Lua function as the callback which gets called automatically when the client closes the (downstream) connection prematurely.</p>
<p>Returns <code class="language-plaintext highlighter-rouge">1</code> if the callback is registered successfully or returns <code class="language-plaintext highlighter-rouge">nil</code> and a string describing the error otherwise.</p>
<p>All the <a href="#nginx-api-for-lua">Nginx API for Lua</a> can be used in the callback function because the function is run in a special “light thread”, just as those “light threads” created by <a href="#ngxthreadspawn">ngx.thread.spawn</a>.</p>
<p>The callback function can decide what to do with the client abortion event all by itself. For example, it can simply ignore the event by doing nothing and the current Lua request handler will continue executing without interruptions. And the callback function can also decide to terminate everything by calling <a href="#ngxexit">ngx.exit</a>, for example,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="k">function</span> <span class="nf">my_cleanup</span><span class="p">()</span>
<span class="c1">-- custom cleanup work goes here, like cancelling a pending DB transaction</span>
<span class="c1">-- now abort all the "light threads" running in the current request handler</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">499</span><span class="p">)</span>
<span class="k">end</span>
<span class="kd">local</span> <span class="n">ok</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">on_abort</span><span class="p">(</span><span class="n">my_cleanup</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">ok</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">ERR</span><span class="p">,</span> <span class="s2">"failed to register the on_abort callback: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">exit</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>
<span class="k">end</span>
</code></pre></div></div>
<p>When <a href="#lua_check_client_abort">lua_check_client_abort</a> is set to <code class="language-plaintext highlighter-rouge">off</code> (which is the default), then this function call will always return the error message “lua_check_client_abort is off”.</p>
<p>According to the current implementation, this function can only be called once in a single request handler; subsequent calls will return the error message “duplicate call”.</p>
<p>This API was first introduced in the <code class="language-plaintext highlighter-rouge">v0.7.4</code> release.</p>
<p>See also <a href="#lua_check_client_abort">lua_check_client_abort</a>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxtimerat">ngx.timer.at</h2>
<p><strong>syntax:</strong> <em>ok, err = ngx.timer.at(delay, callback, user_arg1, user_arg2, …)</em></p>
<p><strong>context:</strong> <em>init_worker_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>Creates an Nginx timer with a user callback function as well as optional user arguments.</p>
<p>The first argument, <code class="language-plaintext highlighter-rouge">delay</code>, specifies the delay for the timer,
in seconds. One can specify fractional seconds like <code class="language-plaintext highlighter-rouge">0.001</code> to mean 1
millisecond here. <code class="language-plaintext highlighter-rouge">0</code> delay can also be specified, in which case the
timer will immediately expire when the current handler yields
execution.</p>
<p>The second argument, <code class="language-plaintext highlighter-rouge">callback</code>, can
be any Lua function, which will be invoked later in a background
“light thread” after the delay specified. The user callback will be
called automatically by the Nginx core with the arguments <code class="language-plaintext highlighter-rouge">premature</code>,
<code class="language-plaintext highlighter-rouge">user_arg1</code>, <code class="language-plaintext highlighter-rouge">user_arg2</code>, and etc, where the <code class="language-plaintext highlighter-rouge">premature</code>
argument takes a boolean value indicating whether it is a premature timer
expiration or not, and <code class="language-plaintext highlighter-rouge">user_arg1</code>, <code class="language-plaintext highlighter-rouge">user_arg2</code>, and etc, are
those (extra) user arguments specified when calling <code class="language-plaintext highlighter-rouge">ngx.timer.at</code>
as the remaining arguments.</p>
<p>Premature timer expiration happens when the Nginx worker process is
trying to shut down, as in an Nginx configuration reload triggered by
the <code class="language-plaintext highlighter-rouge">HUP</code> signal or in an Nginx server shutdown. When the Nginx worker
is trying to shut down, one can no longer call <code class="language-plaintext highlighter-rouge">ngx.timer.at</code> to
create new timers with nonzero delays and in that case <code class="language-plaintext highlighter-rouge">ngx.timer.at</code> will return <code class="language-plaintext highlighter-rouge">nil</code> and
a string describing the error, that is, “process exiting”.</p>
<p>Starting from the <code class="language-plaintext highlighter-rouge">v0.9.3</code> release, it is allowed to create zero-delay timers even when the Nginx worker process starts shutting down.</p>
<p>When a timer expires, the user Lua code in the timer callback is
running in a “light thread” detached completely from the original
request creating the timer. So objects with the same lifetime as the
request creating them, like <a href="#ngxsockettcp">cosockets</a>, cannot be shared between the
original request and the timer user callback function.</p>
<p>Here is a simple example:</p>
<div class="language-nginx highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="k">location</span> <span class="n">/</span> <span class="p">{</span>
<span class="kn">...</span>
<span class="s">log_by_lua</span> <span class="s">'</span>
<span class="s">local</span> <span class="s">function</span> <span class="s">push_data(premature,</span> <span class="s">uri,</span> <span class="s">args,</span> <span class="s">status)</span>
<span class="s">--</span> <span class="s">push</span> <span class="s">the</span> <span class="s">data</span> <span class="s">uri,</span> <span class="s">args,</span> <span class="s">and</span> <span class="s">status</span> <span class="s">to</span> <span class="s">the</span> <span class="s">remote</span>
<span class="s">--</span> <span class="s">via</span> <span class="s">ngx.socket.tcp</span> <span class="s">or</span> <span class="s">ngx.socket.udp</span>
<span class="s">--</span> <span class="s">(one</span> <span class="s">may</span> <span class="s">want</span> <span class="s">to</span> <span class="s">buffer</span> <span class="s">the</span> <span class="s">data</span> <span class="s">in</span> <span class="s">Lua</span> <span class="s">a</span> <span class="s">bit</span> <span class="s">to</span>
<span class="s">--</span> <span class="s">save</span> <span class="nc">I/O</span> <span class="s">operations)</span>
<span class="s">end</span>
<span class="s">local</span> <span class="s">ok,</span> <span class="s">err</span> <span class="p">=</span> <span class="s">ngx.timer.at(0,</span> <span class="s">push_data,</span>
<span class="s">ngx.var.uri,</span> <span class="s">ngx.var.args,</span> <span class="s">ngx.header.status)</span>
<span class="s">if</span> <span class="s">not</span> <span class="s">ok</span> <span class="s">then</span>
<span class="s">ngx.log(ngx.ERR,</span> <span class="s">"failed</span> <span class="s">to</span> <span class="s">create</span> <span class="s">timer:</span> <span class="s">",</span> <span class="s">err)</span>
<span class="s">return</span>
<span class="s">end</span>
<span class="s">'</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>One can also create infinite re-occuring timers, for instance, a timer getting triggered every <code class="language-plaintext highlighter-rouge">5</code> seconds, by calling <code class="language-plaintext highlighter-rouge">ngx.timer.at</code> recursively in the timer callback function. Here is such an example,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">delay</span> <span class="o">=</span> <span class="mi">5</span>
<span class="kd">local</span> <span class="n">handler</span>
<span class="n">handler</span> <span class="o">=</span> <span class="k">function</span> <span class="p">(</span><span class="n">premature</span><span class="p">)</span>
<span class="c1">-- do some routine job in Lua just like a cron job</span>
<span class="k">if</span> <span class="n">premature</span> <span class="k">then</span>
<span class="k">return</span>
<span class="k">end</span>
<span class="kd">local</span> <span class="n">ok</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">timer</span><span class="p">.</span><span class="n">at</span><span class="p">(</span><span class="n">delay</span><span class="p">,</span> <span class="n">handler</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">ok</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">ERR</span><span class="p">,</span> <span class="s2">"failed to create the timer: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
<span class="k">end</span>
<span class="kd">local</span> <span class="n">ok</span><span class="p">,</span> <span class="n">err</span> <span class="o">=</span> <span class="n">ngx</span><span class="p">.</span><span class="n">timer</span><span class="p">.</span><span class="n">at</span><span class="p">(</span><span class="n">delay</span><span class="p">,</span> <span class="n">handler</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">ok</span> <span class="k">then</span>
<span class="n">ngx</span><span class="p">.</span><span class="n">log</span><span class="p">(</span><span class="n">ngx</span><span class="p">.</span><span class="n">ERR</span><span class="p">,</span> <span class="s2">"failed to create the timer: "</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
<span class="k">return</span>
<span class="k">end</span>
</code></pre></div></div>
<p>Because timer callbacks run in the background and their running time
will not add to any client requests response time, they can easily
accumulate in the server and exhaust system resources due to either
Lua programming mistakes or just too much client traffic. To prevent
extreme consequences like crashing the Nginx server, there are
built-in limitations on both the number of “pending timers” and the
number of “running timers” in an Nginx worker process. The “pending
timers” here mean timers that have not yet been expired and “running
timers” are those whose user callbacks are currently running.</p>
<p>The maximal number of pending timers allowed in an Nginx
worker is constrolled by the <a href="#lua_max_pending_timers">lua_max_pending_timers</a>
directive. The maximal number of running timers is controlled by the
<a href="#lua_max_running_timers">lua_max_running_timers</a> directive.</p>
<p>According to the current implementation, each “running timer” will
take one (fake) connection record from the global connection record
list configured by the standard <a href="http://nginx.org/en/docs/ngx_core_module.html#worker_connections">worker_connections</a> directive in
<code class="language-plaintext highlighter-rouge">nginx.conf</code>. So ensure that the
<a href="http://nginx.org/en/docs/ngx_core_module.html#worker_connections">worker_connections</a> directive is set to
a large enough value that takes into account both the real connections
and fake connections required by timer callbacks (as limited by the
<a href="#lua_max_running_timers">lua_max_running_timers</a> directive).</p>
<p>A lot of the Lua APIs for Nginx are enabled in the context of the timer
callbacks, like stream/datagram cosockets (<a href="#ngxsockettcp">ngx.socket.tcp</a> and <a href="#ngxsocketudp">ngx.socket.udp</a>), shared
memory dictionaries (<a href="#ngxshareddict">ngx.shared.DICT</a>), user coroutines (<a href="#ngxthreadspawn">coroutine.<em>](#coroutinecreate)),
user “light threads” ([ngx.thread.</em></a>), <a href="#ngxexit">ngx.exit</a>, <a href="#ngxnow">ngx.now</a>/<a href="#ngxtime">ngx.time</a>,
<a href="#ngxmd5">ngx.md5</a>/<a href="#ngxsha1_bin">ngx.sha1_bin</a>, are all allowed. But the subrequest API (like
<a href="#ngxlocationcapture">ngx.location.capture</a>), the <a href="#ngxreqstart_time">ngx.req.*</a> API, the downstream output API
(like <a href="#ngxsay">ngx.say</a>, <a href="#ngxprint">ngx.print</a>, and <a href="#ngxflush">ngx.flush</a>) are explicitly disabled in
this context.</p>
<p>You can pass most of the standard Lua values (nils, booleans, numbers, strings, tables, closures, file handles, and etc) into the timer callback, either explicitly as user arguments or implicitly as upvalues for the callback closure. There are several exceptions, however: you <em>cannot</em> pass any thread objects returned by <a href="#coroutinecreate">coroutine.create</a> and <a href="#ngxthreadspawn">ngx.thread.spawn</a> or any cosocket objects returned by <a href="#ngxsockettcp">ngx.socket.tcp</a>, <a href="#ngxsocketudp">ngx.socket.udp</a>, and <a href="#ngxreqsocket">ngx.req.socket</a> because these objects lifetime is bound to the request context creating them while the timer callback is detached from the creating requests context (by design) and runs in its own (fake) request context. If you try to share the thread or cosocket objects across the boundary of the creating request, then you will get the “no co ctx found” error (for threads) or “bad request” (for cosockets). It is fine, however, to create all these objects inside your timer callback.</p>
<p>This API was first introduced in the <code class="language-plaintext highlighter-rouge">v0.8.0</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxconfigdebug">ngx.config.debug</h2>
<p><strong>syntax:</strong> <em>debug = ngx.config.debug</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.<em>, init_by_lua</em>, init_worker_by_lua**</p>
<p>This boolean field indicates whether the current Nginx is a debug build, i.e., being built by the <code class="language-plaintext highlighter-rouge">./configure</code> option <code class="language-plaintext highlighter-rouge">--with-debug</code>.</p>
<p>This field was first introduced in the <code class="language-plaintext highlighter-rouge">0.8.7</code>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxconfigprefix">ngx.config.prefix</h2>
<p><strong>syntax:</strong> <em>prefix = ngx.config.prefix()</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.<em>, init_by_lua</em>, init_worker_by_lua**</p>
<p>Returns the Nginx server “prefix” path, as determined by the <code class="language-plaintext highlighter-rouge">-p</code> command-line option when running the nginx executable, or the path specified by the <code class="language-plaintext highlighter-rouge">--prefix</code> command-line option when building Nginx with the <code class="language-plaintext highlighter-rouge">./configure</code> script.</p>
<p>This function was first introduced in the <code class="language-plaintext highlighter-rouge">0.9.2</code>.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxconfignginx_version">ngx.config.nginx_version</h2>
<p><strong>syntax:</strong> <em>ver = ngx.config.nginx_version</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.<em>, init_by_lua</em>, init_worker_by_lua**</p>
<p>This field take an integral value indicating the version number of the current Nginx core being used. For example, the version number <code class="language-plaintext highlighter-rouge">1.4.3</code> results in the Lua number 1004003.</p>
<p>This API was first introduced in the <code class="language-plaintext highlighter-rouge">0.9.3</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxconfignginx_configure">ngx.config.nginx_configure</h2>
<p><strong>syntax:</strong> <em>str = ngx.config.nginx_configure()</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.*, init_by_lua**</p>
<p>This function returns a string for the NGINX <code class="language-plaintext highlighter-rouge">./configure</code> commands arguments string.</p>
<p>This API was first introduced in the <code class="language-plaintext highlighter-rouge">0.9.5</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxconfigngx_lua_version">ngx.config.ngx_lua_version</h2>
<p><strong>syntax:</strong> <em>ver = ngx.config.ngx_lua_version</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.*, init_by_lua**</p>
<p>This field take an integral value indicating the version number of the current <code class="language-plaintext highlighter-rouge">ngx_lua</code> module being used. For example, the version number <code class="language-plaintext highlighter-rouge">0.9.3</code> results in the Lua number 9003.</p>
<p>This API was first introduced in the <code class="language-plaintext highlighter-rouge">0.9.3</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxworkerexiting">ngx.worker.exiting</h2>
<p><strong>syntax:</strong> <em>exiting = ngx.worker.exiting()</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.<em>, init_by_lua</em>, init_worker_by_lua**</p>
<p>This function returns a boolean value indicating whether the current Nginx worker process already starts exiting. Nginx worker process exiting happens on Nginx server quit or configuration reload (aka HUP reload).</p>
<p>This API was first introduced in the <code class="language-plaintext highlighter-rouge">0.9.3</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ngxworkerpid">ngx.worker.pid</h2>
<p><strong>syntax:</strong> <em>pid = ngx.worker.pid()</em></p>
<p><strong>context:</strong> <em>set_by_lua</em>, rewrite_by_lua<em>, access_by_lua</em>, content_by_lua<em>, header_filter_by_lua</em>, body_filter_by_lua<em>, log_by_lua</em>, ngx.timer.<em>, init_by_lua</em>, init_worker_by_lua**</p>
<p>This function returns a Lua number for the process ID (PID) of the current Nginx worker process. This API is more efficient than <code class="language-plaintext highlighter-rouge">ngx.var.pid</code> and can be used in contexts where the <a href="#ngxvarvariable">ngx.var.VARIABLE</a> API cannot be used (like <a href="#init_worker_by_lua">init_worker_by_lua</a>).</p>
<p>This API was first introduced in the <code class="language-plaintext highlighter-rouge">0.9.5</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="ndkset_vardirective">ndk.set_var.DIRECTIVE</h2>
<p><strong>syntax:</strong> <em>res = ndk.set_var.DIRECTIVE_NAME</em></p>
<p><strong>context:</strong> <em>init_worker_by_lua</em>, set_by_lua<em>, rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, header_filter_by_lua<em>, body_filter_by_lua</em>, log_by_lua*, ngx.timer.**</p>
<p>This mechanism allows calling other nginx C modules directives that are implemented by <a href="https://github.com/simpl/ngx_devel_kit">Nginx Devel Kit</a> (NDK)s set_var submodules <code class="language-plaintext highlighter-rouge">ndk_set_var_value</code>.</p>
<p>For example, the following <a href="http://github.com/openresty/set-misc-nginx-module">set-misc-nginx-module</a> directives can be invoked this way:</p>
<ul>
<li><a href="http://github.com/openresty/set-misc-nginx-module#set_quote_sql_str">set_quote_sql_str</a></li>
<li><a href="http://github.com/openresty/set-misc-nginx-module#set_quote_pgsql_str">set_quote_pgsql_str</a></li>
<li><a href="http://github.com/openresty/set-misc-nginx-module#set_quote_json_str">set_quote_json_str</a></li>
<li><a href="http://github.com/openresty/set-misc-nginx-module#set_unescape_uri">set_unescape_uri</a></li>
<li><a href="http://github.com/openresty/set-misc-nginx-module#set_escape_uri">set_escape_uri</a></li>
<li><a href="http://github.com/openresty/set-misc-nginx-module#set_encode_base32">set_encode_base32</a></li>
<li><a href="http://github.com/openresty/set-misc-nginx-module#set_decode_base32">set_decode_base32</a></li>
<li><a href="http://github.com/openresty/set-misc-nginx-module#set_encode_base64">set_encode_base64</a></li>
<li><a href="http://github.com/openresty/set-misc-nginx-module#set_decode_base64">set_decode_base64</a></li>
<li><a href="http://github.com/openresty/set-misc-nginx-module#set_encode_base64">set_encode_hex</a></li>
<li><a href="http://github.com/openresty/set-misc-nginx-module#set_decode_base64">set_decode_hex</a></li>
<li><a href="http://github.com/openresty/set-misc-nginx-module#set_encode_base64">set_sha1</a></li>
<li><a href="http://github.com/openresty/set-misc-nginx-module#set_decode_base64">set_md5</a></li>
</ul>
<p>For instance,</p>
<div class="language-lua highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="kd">local</span> <span class="n">res</span> <span class="o">=</span> <span class="n">ndk</span><span class="p">.</span><span class="n">set_var</span><span class="p">.</span><span class="n">set_escape_uri</span><span class="p">(</span><span class="s1">'a/b'</span><span class="p">);</span>
<span class="c1">-- now res == 'a%2fb'</span>
</code></pre></div></div>
<p>Similarly, the following directives provided by <a href="http://github.com/openresty/encrypted-session-nginx-module">encrypted-session-nginx-module</a> can be invoked from within Lua too:</p>
<ul>
<li><a href="http://github.com/openresty/encrypted-session-nginx-module#set_encrypt_session">set_encrypt_session</a></li>
<li><a href="http://github.com/openresty/encrypted-session-nginx-module#set_decrypt_session">set_decrypt_session</a></li>
</ul>
<p>This feature requires the <a href="https://github.com/simpl/ngx_devel_kit">ngx_devel_kit</a> module.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="coroutinecreate">coroutine.create</h2>
<p><strong>syntax:</strong> <em>co = coroutine.create(f)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, init_by_lua<em>, ngx.timer.</em>, header_filter_by_lua*, body_filter_by_lua**</p>
<p>Creates a user Lua coroutines with a Lua function, and returns a coroutine object.</p>
<p>Similar to the standard Lua <a href="http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.create">coroutine.create</a> API, but works in the context of the Lua coroutines created by ngx_lua.</p>
<p>This API was first usable in the context of <a href="#init_by_lua">init_by_lua*</a> since the <code class="language-plaintext highlighter-rouge">0.9.2</code>.</p>
<p>This API was first introduced in the <code class="language-plaintext highlighter-rouge">v0.6.0</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="coroutineresume">coroutine.resume</h2>
<p><strong>syntax:</strong> <em>ok, … = coroutine.resume(co, …)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, init_by_lua<em>, ngx.timer.</em>, header_filter_by_lua*, body_filter_by_lua**</p>
<p>Resumes the executation of a user Lua coroutine object previously yielded or just created.</p>
<p>Similar to the standard Lua <a href="http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.resume">coroutine.resume</a> API, but works in the context of the Lua coroutines created by ngx_lua.</p>
<p>This API was first usable in the context of <a href="#init_by_lua">init_by_lua*</a> since the <code class="language-plaintext highlighter-rouge">0.9.2</code>.</p>
<p>This API was first introduced in the <code class="language-plaintext highlighter-rouge">v0.6.0</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="coroutineyield">coroutine.yield</h2>
<p><strong>syntax:</strong> <em>… = coroutine.yield(…)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, init_by_lua<em>, ngx.timer.</em>, header_filter_by_lua*, body_filter_by_lua**</p>
<p>Yields the executation of the current user Lua coroutine.</p>
<p>Similar to the standard Lua <a href="http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.yield">coroutine.yield</a> API, but works in the context of the Lua coroutines created by ngx_lua.</p>
<p>This API was first usable in the context of <a href="#init_by_lua">init_by_lua*</a> since the <code class="language-plaintext highlighter-rouge">0.9.2</code>.</p>
<p>This API was first introduced in the <code class="language-plaintext highlighter-rouge">v0.6.0</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="coroutinewrap">coroutine.wrap</h2>
<p><strong>syntax:</strong> <em>co = coroutine.wrap(f)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, init_by_lua<em>, ngx.timer.</em>, header_filter_by_lua*, body_filter_by_lua**</p>
<p>Similar to the standard Lua <a href="http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.wrap">coroutine.wrap</a> API, but works in the context of the Lua coroutines created by ngx_lua.</p>
<p>This API was first usable in the context of <a href="#init_by_lua">init_by_lua*</a> since the <code class="language-plaintext highlighter-rouge">0.9.2</code>.</p>
<p>This API was first introduced in the <code class="language-plaintext highlighter-rouge">v0.6.0</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="coroutinerunning">coroutine.running</h2>
<p><strong>syntax:</strong> <em>co = coroutine.running()</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, init_by_lua<em>, ngx.timer.</em>, header_filter_by_lua*, body_filter_by_lua**</p>
<p>Identical to the standard Lua <a href="http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.running">coroutine.running</a> API.</p>
<p>This API was first usable in the context of <a href="#init_by_lua">init_by_lua*</a> since the <code class="language-plaintext highlighter-rouge">0.9.2</code>.</p>
<p>This API was first enabled in the <code class="language-plaintext highlighter-rouge">v0.6.0</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h2 id="coroutinestatus">coroutine.status</h2>
<p><strong>syntax:</strong> <em>status = coroutine.status(co)</em></p>
<p><strong>context:</strong> <em>rewrite_by_lua</em>, access_by_lua<em>, content_by_lua</em>, init_by_lua<em>, ngx.timer.</em>, header_filter_by_lua*, body_filter_by_lua**</p>
<p>Identical to the standard Lua <a href="http://www.lua.org/manual/5.1/manual.html#pdf-coroutine.status">coroutine.status</a> API.</p>
<p>This API was first usable in the context of <a href="#init_by_lua">init_by_lua*</a> since the <code class="language-plaintext highlighter-rouge">0.9.2</code>.</p>
<p>This API was first enabled in the <code class="language-plaintext highlighter-rouge">v0.6.0</code> release.</p>
<p><a href="#nginx-api-for-lua">Back to TOC</a></p>
<h1 id="obsolete-sections">Obsolete Sections</h1>
<p>This section is just holding obsolete documentation sections that have been either renamed or removed so that existing links over the web are still valid.</p>
<p><a href="#table-of-contents">Back to TOC</a></p>
<h2 id="special-pcre-sequences">Special PCRE Sequences</h2>
<p>This section has been renamed to <a href="#special-escaping-sequences">Special Escaping Sequences</a>.</p>
</div>
<div class="d-print-none"><footer class="article__footer"><meta itemprop="dateModified" content="2019-12-25T00:00:00+01:00"><!-- start custom article footer snippet -->
<!-- end custom article footer snippet -->
<!--
<div align="right"><a type="application/rss+xml" href="/feed.xml" title="S'abonner"><i class="fa fa-rss fa-2x"></i></a>
&emsp;</div>
-->
</footer>
<div class="article__section-navigator clearfix"><div class="previous"><span>PRÉCÉDENT</span><a href="/2019/12/25/nginx-authentification-base-mysql.html">nginx-authentification-base-mysql</a></div><div class="next"><span>SUIVANT</span><a href="/2019/12/25/nmap.html">nmap</a></div></div></div>
</div>
<script>(function() {
var SOURCES = window.TEXT_VARIABLES.sources;
window.Lazyload.js(SOURCES.jquery, function() {
$(function() {
var $this ,$scroll;
var $articleContent = $('.js-article-content');
var hasSidebar = $('.js-page-root').hasClass('layout--page--sidebar');
var scroll = hasSidebar ? '.js-page-main' : 'html, body';
$scroll = $(scroll);
$articleContent.find('.highlight').each(function() {
$this = $(this);
$this.attr('data-lang', $this.find('code').attr('data-lang'));
});
$articleContent.find('h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]').each(function() {
$this = $(this);
$this.append($('<a class="anchor d-print-none" aria-hidden="true"></a>').html('<i class="fas fa-anchor"></i>'));
});
$articleContent.on('click', '.anchor', function() {
$scroll.scrollToAnchor('#' + $(this).parent().attr('id'), 400);
});
});
});
})();
</script>
</div><section class="page__comments d-print-none"></section></article><!-- start custom main bottom snippet -->
<!-- end custom main bottom snippet -->
</div>
</div></div></div></div>
</div><script>(function() {
var SOURCES = window.TEXT_VARIABLES.sources;
window.Lazyload.js(SOURCES.jquery, function() {
var $body = $('body'), $window = $(window);
var $pageRoot = $('.js-page-root'), $pageMain = $('.js-page-main');
var activeCount = 0;
function modal(options) {
var $root = this, visible, onChange, hideWhenWindowScroll = false;
var scrollTop;
function setOptions(options) {
var _options = options || {};
visible = _options.initialVisible === undefined ? false : show;
onChange = _options.onChange;
hideWhenWindowScroll = _options.hideWhenWindowScroll;
}
function init() {
setState(visible);
}
function setState(isShow) {
if (isShow === visible) {
return;
}
visible = isShow;
if (visible) {
activeCount++;
scrollTop = $(window).scrollTop() || $pageMain.scrollTop();
$root.addClass('modal--show');
$pageMain.scrollTop(scrollTop);
activeCount === 1 && ($pageRoot.addClass('show-modal'), $body.addClass('of-hidden'));
hideWhenWindowScroll && window.hasEvent('touchstart') && $window.on('scroll', hide);
$window.on('keyup', handleKeyup);
} else {
activeCount > 0 && activeCount--;
$root.removeClass('modal--show');
$window.scrollTop(scrollTop);
activeCount === 0 && ($pageRoot.removeClass('show-modal'), $body.removeClass('of-hidden'));
hideWhenWindowScroll && window.hasEvent('touchstart') && $window.off('scroll', hide);
$window.off('keyup', handleKeyup);
}
onChange && onChange(visible);
}
function show() {
setState(true);
}
function hide() {
setState(false);
}
function handleKeyup(e) {
// Char Code: 27 ESC
if (e.which === 27) {
hide();
}
}
setOptions(options);
init();
return {
show: show,
hide: hide,
$el: $root
};
}
$.fn.modal = modal;
});
})();
</script><div class="modal modal--overflow page__search-modal d-print-none js-page-search-modal"><script>
(function () {
var SOURCES = window.TEXT_VARIABLES.sources;
window.Lazyload.js(SOURCES.jquery, function() {
// search panel
var search = (window.search || (window.search = {}));
var useDefaultSearchBox = window.useDefaultSearchBox === undefined ?
true : window.useDefaultSearchBox ;
var $searchModal = $('.js-page-search-modal');
var $searchToggle = $('.js-search-toggle');
var searchModal = $searchModal.modal({ onChange: handleModalChange, hideWhenWindowScroll: true });
var modalVisible = false;
search.searchModal = searchModal;
var $searchBox = null;
var $searchInput = null;
var $searchClear = null;
function getModalVisible() {
return modalVisible;
}
search.getModalVisible = getModalVisible;
function handleModalChange(visible) {
modalVisible = visible;
if (visible) {
search.onShow && search.onShow();
useDefaultSearchBox && $searchInput[0] && $searchInput[0].focus();
} else {
search.onShow && search.onHide();
useDefaultSearchBox && $searchInput[0] && $searchInput[0].blur();
setTimeout(function() {
useDefaultSearchBox && ($searchInput.val(''), $searchBox.removeClass('not-empty'));
search.clear && search.clear();
window.pageAsideAffix && window.pageAsideAffix.refresh();
}, 400);
}
}
$searchToggle.on('click', function() {
modalVisible ? searchModal.hide() : searchModal.show();
});
// Char Code: 83 S, 191 /
$(window).on('keyup', function(e) {
if (!modalVisible && !window.isFormElement(e.target || e.srcElement) && (e.which === 83 || e.which === 191)) {
modalVisible || searchModal.show();
}
});
if (useDefaultSearchBox) {
$searchBox = $('.js-search-box');
$searchInput = $searchBox.children('input');
$searchClear = $searchBox.children('.js-icon-clear');
search.getSearchInput = function() {
return $searchInput.get(0);
};
search.getVal = function() {
return $searchInput.val();
};
search.setVal = function(val) {
$searchInput.val(val);
};
$searchInput.on('focus', function() {
$(this).addClass('focus');
});
$searchInput.on('blur', function() {
$(this).removeClass('focus');
});
$searchInput.on('input', window.throttle(function() {
var val = $(this).val();
if (val === '' || typeof val !== 'string') {
search.clear && search.clear();
} else {
$searchBox.addClass('not-empty');
search.onInputNotEmpty && search.onInputNotEmpty(val);
}
}, 400));
$searchClear.on('click', function() {
$searchInput.val(''); $searchBox.removeClass('not-empty');
search.clear && search.clear();
});
}
});
})();
</script><div class="search search--dark">
<div class="main">
<div class="search__header">Recherche</div>
<div class="search-bar">
<div class="search-box js-search-box">
<div class="search-box__icon-search"><i class="fas fa-search"></i></div>
<input id="search-input" type="text" />
<div class="search-box__icon-clear js-icon-clear">
<a><i class="fas fa-times"></i></a>
</div>
</div>
<button class="button button--theme-dark button--pill search__cancel js-search-toggle">
Annuler</button>
</div>
<div id="results-container" class="search-result js-search-result"></div>
</div>
</div>
<!-- Script pointing to search-script.js -->
<script>/*!
* Simple-Jekyll-Search
* Copyright 2015-2020, Christian Fei
* Licensed under the MIT License.
*/
(function(){
'use strict'
var _$Templater_7 = {
compile: compile,
setOptions: setOptions
}
const options = {}
options.pattern = /\{(.*?)\}/g
options.template = ''
options.middleware = function () {}
function setOptions (_options) {
options.pattern = _options.pattern || options.pattern
options.template = _options.template || options.template
if (typeof _options.middleware === 'function') {
options.middleware = _options.middleware
}
}
function compile (data) {
return options.template.replace(options.pattern, function (match, prop) {
const value = options.middleware(prop, data[prop], options.template)
if (typeof value !== 'undefined') {
return value
}
return data[prop] || match
})
}
'use strict';
function fuzzysearch (needle, haystack) {
var tlen = haystack.length;
var qlen = needle.length;
if (qlen > tlen) {
return false;
}
if (qlen === tlen) {
return needle === haystack;
}
outer: for (var i = 0, j = 0; i < qlen; i++) {
var nch = needle.charCodeAt(i);
while (j < tlen) {
if (haystack.charCodeAt(j++) === nch) {
continue outer;
}
}
return false;
}
return true;
}
var _$fuzzysearch_1 = fuzzysearch;
'use strict'
/* removed: const _$fuzzysearch_1 = require('fuzzysearch') */;
var _$FuzzySearchStrategy_5 = new FuzzySearchStrategy()
function FuzzySearchStrategy () {
this.matches = function (string, crit) {
return _$fuzzysearch_1(crit.toLowerCase(), string.toLowerCase())
}
}
'use strict'
var _$LiteralSearchStrategy_6 = new LiteralSearchStrategy()
function LiteralSearchStrategy () {
this.matches = function (str, crit) {
if (!str) return false
str = str.trim().toLowerCase()
crit = crit.trim().toLowerCase()
return crit.split(' ').filter(function (word) {
return str.indexOf(word) >= 0
}).length === crit.split(' ').length
}
}
'use strict'
var _$Repository_4 = {
put: put,
clear: clear,
search: search,
setOptions: __setOptions_4
}
/* removed: const _$FuzzySearchStrategy_5 = require('./SearchStrategies/FuzzySearchStrategy') */;
/* removed: const _$LiteralSearchStrategy_6 = require('./SearchStrategies/LiteralSearchStrategy') */;
function NoSort () {
return 0
}
const data = []
let opt = {}
opt.fuzzy = false
opt.limit = 10
opt.searchStrategy = opt.fuzzy ? _$FuzzySearchStrategy_5 : _$LiteralSearchStrategy_6
opt.sort = NoSort
opt.exclude = []
function put (data) {
if (isObject(data)) {
return addObject(data)
}
if (isArray(data)) {
return addArray(data)
}
return undefined
}
function clear () {
data.length = 0
return data
}
function isObject (obj) {
return Boolean(obj) && Object.prototype.toString.call(obj) === '[object Object]'
}
function isArray (obj) {
return Boolean(obj) && Object.prototype.toString.call(obj) === '[object Array]'
}
function addObject (_data) {
data.push(_data)
return data
}
function addArray (_data) {
const added = []
clear()
for (let i = 0, len = _data.length; i < len; i++) {
if (isObject(_data[i])) {
added.push(addObject(_data[i]))
}
}
return added
}
function search (crit) {
if (!crit) {
return []
}
return findMatches(data, crit, opt.searchStrategy, opt).sort(opt.sort)
}
function __setOptions_4 (_opt) {
opt = _opt || {}
opt.fuzzy = _opt.fuzzy || false
opt.limit = _opt.limit || 10
opt.searchStrategy = _opt.fuzzy ? _$FuzzySearchStrategy_5 : _$LiteralSearchStrategy_6
opt.sort = _opt.sort || NoSort
opt.exclude = _opt.exclude || []
}
function findMatches (data, crit, strategy, opt) {
const matches = []
for (let i = 0; i < data.length && matches.length < opt.limit; i++) {
const match = findMatchesInObject(data[i], crit, strategy, opt)
if (match) {
matches.push(match)
}
}
return matches
}
function findMatchesInObject (obj, crit, strategy, opt) {
for (const key in obj) {
if (!isExcluded(obj[key], opt.exclude) && strategy.matches(obj[key], crit)) {
return obj
}
}
}
function isExcluded (term, excludedTerms) {
for (let i = 0, len = excludedTerms.length; i < len; i++) {
const excludedTerm = excludedTerms[i]
if (new RegExp(excludedTerm).test(term)) {
return true
}
}
return false
}
/* globals ActiveXObject:false */
'use strict'
var _$JSONLoader_2 = {
load: load
}
function load (location, callback) {
const xhr = getXHR()
xhr.open('GET', location, true)
xhr.onreadystatechange = createStateChangeListener(xhr, callback)
xhr.send()
}
function createStateChangeListener (xhr, callback) {
return function () {
if (xhr.readyState === 4 && xhr.status === 200) {
try {
callback(null, JSON.parse(xhr.responseText))
} catch (err) {
callback(err, null)
}
}
}
}
function getXHR () {
return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP')
}
'use strict'
var _$OptionsValidator_3 = function OptionsValidator (params) {
if (!validateParams(params)) {
throw new Error('-- OptionsValidator: required options missing')
}
if (!(this instanceof OptionsValidator)) {
return new OptionsValidator(params)
}
const requiredOptions = params.required
this.getRequiredOptions = function () {
return requiredOptions
}
this.validate = function (parameters) {
const errors = []
requiredOptions.forEach(function (requiredOptionName) {
if (typeof parameters[requiredOptionName] === 'undefined') {
errors.push(requiredOptionName)
}
})
return errors
}
function validateParams (params) {
if (!params) {
return false
}
return typeof params.required !== 'undefined' && params.required instanceof Array
}
}
'use strict'
var _$utils_9 = {
merge: merge,
isJSON: isJSON
}
function merge (defaultParams, mergeParams) {
const mergedOptions = {}
for (const option in defaultParams) {
mergedOptions[option] = defaultParams[option]
if (typeof mergeParams[option] !== 'undefined') {
mergedOptions[option] = mergeParams[option]
}
}
return mergedOptions
}
function isJSON (json) {
try {
if (json instanceof Object && JSON.parse(JSON.stringify(json))) {
return true
}
return false
} catch (err) {
return false
}
}
var _$src_8 = {};
(function (window) {
'use strict'
let options = {
searchInput: null,
resultsContainer: null,
json: [],
success: Function.prototype,
searchResultTemplate: '<li><a href="{url}" title="{desc}">{title}</a></li>',
templateMiddleware: Function.prototype,
sortMiddleware: function () {
return 0
},
noResultsText: 'No results found',
limit: 10,
fuzzy: false,
debounceTime: null,
exclude: []
}
let debounceTimerHandle
const debounce = function (func, delayMillis) {
if (delayMillis) {
clearTimeout(debounceTimerHandle)
debounceTimerHandle = setTimeout(func, delayMillis)
} else {
func.call()
}
}
const requiredOptions = ['searchInput', 'resultsContainer', 'json']
/* removed: const _$Templater_7 = require('./Templater') */;
/* removed: const _$Repository_4 = require('./Repository') */;
/* removed: const _$JSONLoader_2 = require('./JSONLoader') */;
const optionsValidator = _$OptionsValidator_3({
required: requiredOptions
})
/* removed: const _$utils_9 = require('./utils') */;
window.SimpleJekyllSearch = function (_options) {
const errors = optionsValidator.validate(_options)
if (errors.length > 0) {
throwError('You must specify the following required options: ' + requiredOptions)
}
options = _$utils_9.merge(options, _options)
_$Templater_7.setOptions({
template: options.searchResultTemplate,
middleware: options.templateMiddleware
})
_$Repository_4.setOptions({
fuzzy: options.fuzzy,
limit: options.limit,
sort: options.sortMiddleware,
exclude: options.exclude
})
if (_$utils_9.isJSON(options.json)) {
initWithJSON(options.json)
} else {
initWithURL(options.json)
}
const rv = {
search: search
}
typeof options.success === 'function' && options.success.call(rv)
return rv
}
function initWithJSON (json) {
_$Repository_4.put(json)
registerInput()
}
function initWithURL (url) {
_$JSONLoader_2.load(url, function (err, json) {
if (err) {
throwError('failed to get JSON (' + url + ')')
}
initWithJSON(json)
})
}
function emptyResultsContainer () {
options.resultsContainer.innerHTML = ''
}
function appendToResultsContainer (text) {
options.resultsContainer.innerHTML += text
}
function registerInput () {
options.searchInput.addEventListener('input', function (e) {
if (isWhitelistedKey(e.which)) {
emptyResultsContainer()
debounce(function () { search(e.target.value) }, options.debounceTime)
}
})
}
function search (query) {
if (isValidQuery(query)) {
emptyResultsContainer()
render(_$Repository_4.search(query), query)
}
}
function render (results, query) {
const len = results.length
if (len === 0) {
return appendToResultsContainer(options.noResultsText)
}
for (let i = 0; i < len; i++) {
results[i].query = query
appendToResultsContainer(_$Templater_7.compile(results[i]))
}
}
function isValidQuery (query) {
return query && query.length > 0
}
function isWhitelistedKey (key) {
return [13, 16, 20, 37, 38, 39, 40, 91].indexOf(key) === -1
}
function throwError (message) {
throw new Error('SimpleJekyllSearch --- ' + message)
}
})(window)
}());
</script>
<!-- Configuration -->
<script>
SimpleJekyllSearch({
searchInput: document.getElementById('search-input'),
resultsContainer: document.getElementById('results-container'),
noResultsText: '<p>Aucun résultat!</p>',
json: '/search.json',
searchResultTemplate: '<li><a href="{url}">{date}&nbsp;{title}</a>&nbsp;(Création {create})</li>'
})
</script>
</div></div>
<script>(function() {
var SOURCES = window.TEXT_VARIABLES.sources;
window.Lazyload.js(SOURCES.jquery, function() {
function scrollToAnchor(anchor, duration, callback) {
var $root = this;
$root.animate({ scrollTop: $(anchor).position().top }, duration, function() {
window.history.replaceState(null, '', window.location.href.split('#')[0] + anchor);
callback && callback();
});
}
$.fn.scrollToAnchor = scrollToAnchor;
});
})();
(function() {
var SOURCES = window.TEXT_VARIABLES.sources;
window.Lazyload.js(SOURCES.jquery, function() {
function affix(options) {
var $root = this, $window = $(window), $scrollTarget, $scroll,
offsetBottom = 0, scrollTarget = window, scroll = window.document, disabled = false, isOverallScroller = true,
rootTop, rootLeft, rootHeight, scrollBottom, rootBottomTop,
hasInit = false, curState;
function setOptions(options) {
var _options = options || {};
_options.offsetBottom && (offsetBottom = _options.offsetBottom);
_options.scrollTarget && (scrollTarget = _options.scrollTarget);
_options.scroll && (scroll = _options.scroll);
_options.disabled !== undefined && (disabled = _options.disabled);
$scrollTarget = $(scrollTarget);
isOverallScroller = window.isOverallScroller($scrollTarget[0]);
$scroll = $(scroll);
}
function preCalc() {
top();
rootHeight = $root.outerHeight();
rootTop = $root.offset().top + (isOverallScroller ? 0 : $scrollTarget.scrollTop());
rootLeft = $root.offset().left;
}
function calc(needPreCalc) {
needPreCalc && preCalc();
scrollBottom = $scroll.outerHeight() - offsetBottom - rootHeight;
rootBottomTop = scrollBottom - rootTop;
}
function top() {
if (curState !== 'top') {
$root.removeClass('fixed').css({
left: 0,
top: 0
});
curState = 'top';
}
}
function fixed() {
if (curState !== 'fixed') {
$root.addClass('fixed').css({
left: rootLeft + 'px',
top: 0
});
curState = 'fixed';
}
}
function bottom() {
if (curState !== 'bottom') {
$root.removeClass('fixed').css({
left: 0,
top: rootBottomTop + 'px'
});
curState = 'bottom';
}
}
function setState() {
var scrollTop = $scrollTarget.scrollTop();
if (scrollTop >= rootTop && scrollTop <= scrollBottom) {
fixed();
} else if (scrollTop < rootTop) {
top();
} else {
bottom();
}
}
function init() {
if(!hasInit) {
var interval, timeout;
calc(true); setState();
// run calc every 100 millisecond
interval = setInterval(function() {
calc();
}, 100);
timeout = setTimeout(function() {
clearInterval(interval);
}, 45000);
window.pageLoad.then(function() {
setTimeout(function() {
clearInterval(interval);
clearTimeout(timeout);
}, 3000);
});
$scrollTarget.on('scroll', function() {
disabled || setState();
});
$window.on('resize', function() {
disabled || (calc(true), setState());
});
hasInit = true;
}
}
setOptions(options);
if (!disabled) {
init();
}
$window.on('resize', window.throttle(function() {
init();
}, 200));
return {
setOptions: setOptions,
refresh: function() {
calc(true, { animation: false }); setState();
}
};
}
$.fn.affix = affix;
});
})();
(function() {
var SOURCES = window.TEXT_VARIABLES.sources;
window.Lazyload.js(SOURCES.jquery, function() {
function toc(options) {
var $root = this, $window = $(window), $scrollTarget, $scroller, $tocUl = $('<ul class="toc toc--ellipsis"></ul>'), $tocLi, $headings, $activeLast, $activeCur,
selectors = 'h1,h2,h3', container = 'body', scrollTarget = window, scroller = 'html, body', disabled = false,
headingsPos, scrolling = false, hasRendered = false, hasInit = false;
function setOptions(options) {
var _options = options || {};
_options.selectors && (selectors = _options.selectors);
_options.container && (container = _options.container);
_options.scrollTarget && (scrollTarget = _options.scrollTarget);
_options.scroller && (scroller = _options.scroller);
_options.disabled !== undefined && (disabled = _options.disabled);
$headings = $(container).find(selectors).filter('[id]');
$scrollTarget = $(scrollTarget);
$scroller = $(scroller);
}
function calc() {
headingsPos = [];
$headings.each(function() {
headingsPos.push(Math.floor($(this).position().top));
});
}
function setState(element, disabled) {
var scrollTop = $scrollTarget.scrollTop(), i;
if (disabled || !headingsPos || headingsPos.length < 1) { return; }
if (element) {
$activeCur = element;
} else {
for (i = 0; i < headingsPos.length; i++) {
if (scrollTop >= headingsPos[i]) {
$activeCur = $tocLi.eq(i);
} else {
$activeCur || ($activeCur = $tocLi.eq(i));
break;
}
}
}
$activeLast && $activeLast.removeClass('active');
($activeLast = $activeCur).addClass('active');
}
function render() {
if(!hasRendered) {
$root.append($tocUl);
$headings.each(function() {
var $this = $(this);
$tocUl.append($('<li></li>').addClass('toc-' + $this.prop('tagName').toLowerCase())
.append($('<a></a>').text($this.text()).attr('href', '#' + $this.prop('id'))));
});
$tocLi = $tocUl.children('li');
$tocUl.on('click', 'a', function(e) {
e.preventDefault();
var $this = $(this);
scrolling = true;
setState($this.parent());
$scroller.scrollToAnchor($this.attr('href'), 400, function() {
scrolling = false;
});
});
}
hasRendered = true;
}
function init() {
var interval, timeout;
if(!hasInit) {
render(); calc(); setState(null, scrolling);
// run calc every 100 millisecond
interval = setInterval(function() {
calc();
}, 100);
timeout = setTimeout(function() {
clearInterval(interval);
}, 45000);
window.pageLoad.then(function() {
setTimeout(function() {
clearInterval(interval);
clearTimeout(timeout);
}, 3000);
});
$scrollTarget.on('scroll', function() {
disabled || setState(null, scrolling);
});
$window.on('resize', window.throttle(function() {
if (!disabled) {
render(); calc(); setState(null, scrolling);
}
}, 100));
}
hasInit = true;
}
setOptions(options);
if (!disabled) {
init();
}
$window.on('resize', window.throttle(function() {
init();
}, 200));
return {
setOptions: setOptions
};
}
$.fn.toc = toc;
});
})();
/*(function () {
})();*/
</script><script>
/* toc must before affix, since affix need to konw toc' height. */(function() {
var SOURCES = window.TEXT_VARIABLES.sources;
var TOC_SELECTOR = window.TEXT_VARIABLES.site.toc.selectors;
window.Lazyload.js(SOURCES.jquery, function() {
var $window = $(window);
var $articleContent = $('.js-article-content');
var $tocRoot = $('.js-toc-root'), $col2 = $('.js-col-aside');
var toc;
var tocDisabled = false;
var hasSidebar = $('.js-page-root').hasClass('layout--page--sidebar');
var hasToc = $articleContent.find(TOC_SELECTOR).length > 0;
function disabled() {
return $col2.css('display') === 'none' || !hasToc;
}
tocDisabled = disabled();
toc = $tocRoot.toc({
selectors: TOC_SELECTOR,
container: $articleContent,
scrollTarget: hasSidebar ? '.js-page-main' : null,
scroller: hasSidebar ? '.js-page-main' : null,
disabled: tocDisabled
});
$window.on('resize', window.throttle(function() {
tocDisabled = disabled();
toc && toc.setOptions({
disabled: tocDisabled
});
}, 100));
});
})();
(function() {
var SOURCES = window.TEXT_VARIABLES.sources;
window.Lazyload.js(SOURCES.jquery, function() {
var $window = $(window), $pageFooter = $('.js-page-footer');
var $pageAside = $('.js-page-aside');
var affix;
var tocDisabled = false;
var hasSidebar = $('.js-page-root').hasClass('layout--page--sidebar');
affix = $pageAside.affix({
offsetBottom: $pageFooter.outerHeight(),
scrollTarget: hasSidebar ? '.js-page-main' : null,
scroller: hasSidebar ? '.js-page-main' : null,
scroll: hasSidebar ? $('.js-page-main').children() : null,
disabled: tocDisabled
});
$window.on('resize', window.throttle(function() {
affix && affix.setOptions({
disabled: tocDisabled
});
}, 100));
window.pageAsideAffix = affix;
});
})();
</script><!---->
</div>
<script>(function () {
var $root = document.getElementsByClassName('root')[0];
if (window.hasEvent('touchstart')) {
$root.dataset.isTouch = true;
document.addEventListener('touchstart', function(){}, false);
}
})();
</script>
</body>
</html>