Skip to content

vhost: Hostname matching library for nginx-module-lua


If you haven't set up RPM repository subscription, sign up. Then you can proceed with the following steps.

CentOS/RHEL 7 or Amazon Linux 2

yum -y install
yum -y install lua-resty-vhost

CentOS/RHEL 8+, Fedora Linux, Amazon Linux 2023

yum -y install
yum -y install lua5.1-resty-vhost

To use this Lua library with NGINX, ensure that nginx-module-lua is installed.

This document describes lua-resty-vhost v0.1 released on Oct 14 2016.

Library for matching hostnames to values. Supports wildcard and .hostname.tld syntax in the same way as Nginx's server_name directive.

Keys beginning with . or *. will match apex and all sub-domains, longest match wins. Non-wildcard matches always win.

Regex matches and prefix wildcards are not supported.


init_by_lua_block {
    local vhost = require("resty.vhost")
    my_vhost = vhost:new()
    local ok, err = my_vhost:insert("",      { key = "",          cert = "" })
    local ok, err = my_vhost:insert("",  { key = "",          cert = "" })
    local ok, err = my_vhost:insert("", { key = "", cert = "" })
    local ok, err = my_vhost:insert("", { key = "",     cert = "" })

server {
    listen 80 default_server;
    listen 443 ssl default_server;
    server_name vhost;

    ssl_certificate         /path/to/default/cert.crt;
    ssl_certificate_key     /path/to/default/key.crt;

    ssl_certificate_by_lua_block {
        local val, err = my_vhost:lookup(require("ngx.ssl").server_name())
        if not val then
            ngx.log(ngx.ERR, err)
            ngx.log(ngx.DEBUG, "Match, setting certs: ", val.cert, " ", val.key)
            -- set_certs_somehow(val)

    location / {
        content_by_lua_block {
            local val, err = my_vhost:lookup(
            if val then
                -- do something based on val
                ngx.say("Matched: ", val.cert)
                if err then
                    ngx.log(ngx.ERR, err)



syntax: my_vhost, err = vhost:new(size?)

Creates a new instance of resty-vhost with an optional initial size


syntax: ok, err = my_vhost:insert(key, value)

Adds a new hostname key with associated value.

Keys must be strings.

Returns false and an error message on failure.


syntax: val, err = my_vhost:lookup(hostname)

Retrieves value for best matching hostname entry.

Returns nil and an error message on failure


  • Regex matches
  • Prefix matches
  • Trie compression


You may find additional configuration tips and documentation for this module in the GitHub repository for nginx-module-vhost.