Migrating from ngx_mruby 2.x to 3.0.0
This guide is for moving scripts, configurations and builds from ngx_mruby 2.x to ngx_mruby 3.0.0. Each change that it covers is described once, under Behavior changes: read before upgrading in the release notes of v3.0.0: what 2.x did, what 3.0.0 does, what is affected and what to do. This guide links to each of those entries and adds the steps and examples: how to find the scripts and builds that an entry affects, what a change looks like in a script, and how to check the result. Read the release notes of the 2.x releases newer than the version you run first (docs/releases).
ngx_mruby 2.x bundles mruby 3.3.0. The development line of ngx_mruby 3
bundles mruby 4.1.0-rc2, the second release candidate of mruby 4.1.0. The
v3 plan (docs/proposals/v3-plan.md, section 7, decision 1) sets mruby
4.1.0 as the mruby of v3; the owner chose on 2026-10-29 to bundle
4.1.0-rc2 instead of waiting for the tag, and the development line moves to
4.1.0 when it is tagged. The entries of the bundled mruby are the changes
that were found and measured for ngx_mruby, not a complete list. mruby’s
own lists of user-visible changes are doc/mruby3.4.md, doc/mruby4.0.md
and, for 4.1, NEWS.md in mruby/.
- Check how you build the module: Builds.
- Find the directives that 3.0.0 refuses or runs in more locations, and change them: Configurations.
- Find the scripts that an entry affects, and change them: Scripts.
- Update log parsers and alerts: Log monitoring.
- If you maintain an mrbgem or other C code that uses the mruby C API, check it: C extensions and mrbgems.
- Check the result: Checking the result.
Builds
Section titled “Builds”-
Build with Ruby 3.0 or later: the build of the bundled mruby stops on Ruby 2.x (Building the bundled mruby needs Ruby 3.0 or later).
ruby --versionprints the version of the Ruby onPATH. -
Build with OpenSSL 3.0 or later, also for
--with-openssl-src:DigestandSecureRandomof the default build come from gems of ngx_mruby that use itsEVP_MACandRAND_bytesAPIs, and the build stops on OpenSSL 1.1.1, LibreSSL and BoringSSL (DigestandSecureRandomcome from gems of ngx_mruby that need OpenSSL 3.0 or later).openssl versionprints the version of theopensslcommand onPATH. The headers that the build uses can be of another version; a build with--with-openssl-srcuses the headers of that source tree. On macOS,configurefinds an OpenSSL of Homebrew under/opt/homebrew/opt/opensslor/usr/local/opt/openssl. For an OpenSSL 3 in another place, give its directories to the build, for example:export NGX_MRUBY_CFLAGS="-I$(brew --prefix openssl@3)/include"export NGX_MRUBY_LDFLAGS="-L$(brew --prefix openssl@3)/lib"A
build_config.rbof your own that adds iij/mruby-digest or monochromegane/mruby-secure-random drops that line: the default gems have the same gem names. -
With the
build_config.rbof this release, rebuild the module; the bundled mruby is built with it (The bundled mruby is 4.1.0-rc2 instead of 3.3.0). -
With a
build_config.rbof your own (Abuild_config.rbof your own needs the core gem changes of mruby 4.1), find the lines that select core gems:grep -nE 'gembox|mruby-print|hal-posix|mruby-task|mruby-encoding|mruby-sleep|mruby-env|mruby-process|regexp|ngx_mruby_core_gems' build_config.rbTo keep the core gems that the default build of ngx_mruby takes, copy
NGX_MRUBY_CORE_GEMSandngx_mruby_core_gemsfrom thebuild_config.rbof this release, and callngx_mruby_core_gems(conf)in place ofconf.gembox 'full-core', as that file does. A build that needs fewer gems passesNGX_MRUBY_CORE_GEMS - %w[...]. To add a gem that the list leaves out, follow Core gems. -
A build from a new checkout or a source archive gets the third-party mrbgems at the commits that
build_config.rb.lockrecords (The third-party mrbgems are built at the commits thatbuild_config.rb.lockrecords). In a tree that keepsmruby/build, remove it after a change of the lock, before the next build; otherwise rake stops withfatal: reference is not a treewhen a clone does not have the new commit:rm -rf mruby/buildTo build a gem at another commit, follow Gem commits.
-
The default build no longer has the auto-ssl mrbgem and the classes that came with it (The default build leaves out the auto-ssl mrbgem and the classes that came with it). Scripts says how to find the scripts that use them.
-
No build of this release has the auto-ssl mrbgem, and the mruby build no longer reads
NGX_MRUBY_AUTO_SSL(The auto-ssl mrbgem andNGX_MRUBY_AUTO_SSLare removed). Remove the variable from the environment of your builds; it has no effect. A server that gets its certificates withNginx::SSL::ACMEmoves to nginx’s ngx_http_ (nginx-acme) before the upgrade, or stays on 2.x. This finds the builds and the configurations that use them:acme_ module grep -rnE 'NGX_MRUBY_AUTO_SSL|auto-ssl|Nginx::SSL::ACME' /path/to/build/scripts /path/to/nginx/conf -
With
./configure --with-mruby-incdir, add<mruby_root>/build/host/includeto the list of directories (Sources that includemruby.hneed the generated headers). -
With mrbgems of your own or of third parties, see C extensions and mrbgems.
Configurations
Section titled “Configurations”-
nginx -trefuses a stream hook given twice in one context: look in eachstream {}block and each of itsserver {}blocks for more than one ofmruby_streamandmruby_stream_code, and in eachstream {}block for more than one ofmruby_stream_initandmruby_stream_init_code, ofmruby_stream_init_workerandmruby_stream_init_worker_code, or ofmruby_stream_exit_workerandmruby_stream_exit_worker_code. Keep the later directive of each, whose code ran on 2.x, and remove the others.nginx -twith the module of 3.0.0 names the second directive and its line:nginx: [emerg] "mruby_stream_code" directive is duplicated in /etc/nginx/nginx.conf:42One directive in the
stream {}block and one in aserver {}stay valid, and the server runs its own code. An alert that matches themrb_string(...) load failedline of a stream directive whose file cannot be read matchesmrb_file(as well: such a line is nowmrb_file(PATH) open failed, as for the HTTP directives. -
Output filters given at
httporserverlevel, or in a location, run in the locations below them: find the filter directives,grep -rnE 'mruby_output_(header|body)_filter' /etc/nginxand, for each, the block that holds it. A filter in the
http {}block now runs in every location of every server, one in aserver {}block in every location of the server, and one in alocationin its nested locations and itsifblocks, unless such a level gives a filter of the same kind of its own. Check that the filter can run for every response there, such as those of static files and upstreams, and move a filter that should run in some locations only into those locations. On 2.x, such a filter ran in none of these locations, except that one in aserver {}block ran for the requests that matched no location.
Scripts
Section titled “Scripts”Most entries name a method that you can search for. This finds them in the
script files of a configuration (replace /path/to/scripts with the
directories of the files that the *_handler directives name):
grep -rnE 'valid_encoding\?|allbits\?|anybits\?|nobits\?|remove_const|module_function|append_features|prepend_features|extend_object|singleton_method_added|\.(included|extended|prepended|inherited|method_added)\(|initialize_copy|respond_to_missing|respond_to\?|method_defined\?|method_missing|instance_methods|\.methods|iv_var|default_proc *=|FileTest|srand|Random\.new|Set\.new|Set\[|flatten_merge|RuntimeError|\.server *=|upstream_server *=|SystemStackError' /path/to/scriptsSearch the inline code of the *_code directives in the nginx.conf
files the same way. The items below say what to look for where a name is
not enough, and show the change.
-
Hash#inspectandHash#to_suse a new format: look forinspect,to_s,"#{...}"andsprintforformatwith%swhere the value can be a Hash or an Array of Hashes, and for=>in the strings that a script or a test compares with.h = {"q" => "x"}Nginx.rputs h.to_s # 2.x: {"q"=>"x"} 3.0.0: {"q" => "x"}Nginx.rputs JSON.generate(h) # {"q":"x"} on both -
Set#inspectandSet#to_suse a new format, andSet#flatten_mergeis removed: the same search for a Set;set.to_a.join(",")gives the same string on both versions. The search above also findsflatten_merge:s.flatten_merge(t)becomess.merge(Set.new(t).flatten), which gives on both versions the Set thats.flatten_merge(t)gave on 2.x, whentis a Set or an Array.s.merge(t.flatten)gives that Set only whentis a Set: for an Arrayt,Array#flattenflattens the Arrays inside it and keeps the Sets, whereflatten_mergedid the opposite:t = [2, Set.new([3])]Set.new([1]).flatten_merge(t) # 2.x: the Set of 1, 2 and 3 3.0.0: NoMethodErrorSet.new([1]).merge(Set.new(t).flatten) # the Set of 1, 2 and 3 on bothSet.new([1]).merge(t.flatten) # the Set of 1, 2 and a Set that holds 3, on both -
The message of
NoMethodErrornames the class of the receiver: look formessagenext torescue NoMethodError, and forundefined methodin scripts.e.message == "undefined method 'foo'" # 2.x: true 3.0.0: false (the message goes on with " for NilClass")Rescue
NoMethodErroritself instead of comparing the message. -
privateandprotectedare enforced: look for calls, with a receiver other thanself, ofinitialize,initialize_copy,respond_to_missing?andmethod_missing, of methods defined withdefat the top level, ofKernelmethods such asraise,sprintfandputs, and of methods belowprivateorprotected. In handler code, a method defined withdefat the top level stays public, and calls of it with a receiver need no change (the proposal for #502, section 1.4). Calls onKernelitself, such asKernel.Integer(x), work on both versions; aKernelmethod called on another object, such as1.Integer("3"), raises. Aprotectedmethod can be called with a receiver of the same class from a method of that class, as in CRuby. The search above findsinstance_methodsandmethods, which leave private methods out. Checkingrespond_to?before such a call does not help: it returnstruefor a private method.class Routerdef call(r)pick(r) # no receiver: works on bothendprivatedef pick(r)r.uriendendRouter.new.pick(r) # 2.x: works 3.0.0: NoMethodErrorRouter.new.send(:pick, r) # works on both1.Integer("3") # 2.x: 3 3.0.0: NoMethodError (private method 'Integer' called for Integer)Kernel.Integer("3") # 3 on bothInteger("3") # 3 on both -
Module#remove_const,#private,#public,#protected,#module_functionand the hooks are private: the search above finds most of them; look also for.private(,.public(and.protected(called on a class or module. For example,Foo.remove_const(:X)becomesFoo.send(:remove_const, :X). -
Overrides of
append_features,prepend_featuresandextend_objectare not called: the search above finds them.module Plugindef self.append_features(base) # 3.0.0: never called, and no errorbase.extend(ClassMethods)superendendmodule Plugindef self.included(base) # called on bothbase.extend(ClassMethods)endend -
allbits?,anybits?andnobits?are methods ofIntegeronly: the search above finds them;x.allbits?(1)on a Float becomesx.to_i.allbits?(1). -
FileTestis a module: the search above findsFileTest; only uses other than calls of its methods (FileTest.exist?and so on) need a change. -
Assigning a constant in a method body is a
SyntaxError: compiling the scripts finds it (see Checking the result).def setupTable = {} # 3.0.0: SyntaxError when the script is compiledObject.const_set(:Table, {}) # works on bothend -
"#@ivar","#@@cvar"and"#$global"in a string interpolate the variable: look for#@and#$in double-quoted strings, heredocs and backquoted commands. The search also finds comments; read each line that it finds:grep -rnE '#[@$]' /path/to/scripts@id = 7Nginx.rputs "Ticket #@id" # 2.x: Ticket #@id 3.0.0: Ticket 7Nginx.rputs "Ticket \#@id" # Ticket #@id on bothNginx.rputs 'Ticket #@id' # Ticket #@id on both -
An
Array, aHashor aStructthat holds itself can be compared: the search above findsSystemStackError. Only a script that rescues it around such a comparison needs a change. -
Float values have no bit operations: look for
<<,>>,&,|,^and~applied to a value that can be a Float: the result ofto_f, ofFloat()or of arithmetic with a Float. The entry says how to get the number that 2.x gave.x = 1.5x << 1 # 2.x: 3 3.0.0: NoMethodError(x * 2).to_i # 3, the number of 2.x for x << 1x.to_i << 1 # 2, another number -
String#valid_encoding?is not in the default build: the search above finds it. With the defaultbuild_config.rbof 2.x the method returnedtruefor every string, so a check like this one never rejected a request and can be removed:Nginx.return Nginx::HTTP_BAD_REQUEST unless s.valid_encoding? -
A seeded
Randomgives other numbers: the search above findssrandandRandom.new; look also for tests that expect the numbers of a seeded generator. -
Hash#default_proc=raisesTypeErrorfor an object that is not a Proc: the search above finds it; pass a Proc, for exampleh.default_proc = proc { |hash, key| hash[key] = [] }. -
yieldwith keyword arguments to a block with keyword parameters works: nothing to change; arescue ArgumentErrorthat was there for this case is no longer reached. -
A
returninside a block or aforbody of handler code ends the code: nothing to change in the scripts. Areturninside a block or the body offorat the top level of handler code no longer raisesLocalJumpError: the handler answers with the response that its code set before thereturn, where 2.x answered 500 (2.7.0 answered 200 with the output that a content handler had written before it). Log alerts onunexpected return (LocalJumpError)no longer fire for it. -
A content handler that ends without output answers 200 with an empty body instead of 500: look at the
mruby_content_handlerandmruby_content_handler_codehandlers that can end without writing a body: a handler that writes only when a condition holds, one that passes a value that can be""orniltoNginx.rputs, one that only sets response headers, and one that ends withNginx.return Nginx::HTTP_OKor another status from 200 to 299 other than 201 and 204. On 3.0.0 they answer that status (200 when none is set) withContent-Length: 0; on 2.7.1 they answered 500. A handler that relied on the 500 sets the status that it means:body = Nginx::Request.new.headers_in["X-Answer"].to_sNginx.rputs body # body "": 2.7.1 answers 500 3.0.0 answers 200 with Content-Length: 0if body.empty?Nginx.return Nginx::HTTP_NOT_FOUND # 404 on bothelseNginx.rputs bodyend -
An output body filter that ends with an empty body sends the response instead of closing the connection: nothing to change. A body filter that sets
""withNginx::Filter#body=or#output, or leaves the body of a response without a body empty, sends the status withContent-Length: 0, where 2.7.2 and earlier closed the connection without a byte; 2.7.3 sends it as well. -
The accessors of
Nginx::Varbecome methods ofNginx::Varat their first use in a worker: the search above findsrespond_to?,method_defined?,instance_methodsandmethods; look at the ones on anNginx::Varor onNginx::Varitself. Their answer for a variable now depends on whether the worker has served an access of the name before. Useexist?instead:v = Nginx::Var.newv.respond_to?(:request_method) # 2.x: false 3.0.0: true after the first v.request_method in the workerv.exist?("request_method") # true on bothAlso look for methods that the scripts define on
ObjectorKernel, for example with adefat the top level of handler code, whose name is also the name of a variable that a script reads withv.NAME. Once the accessor exists in a worker,v.NAMEreads the variable instead of calling such a method. Rename the method. The search also findsmethod_missing: a script that wrapsNginx::Var#method_missing, for example with a module prepended toNginx::Varwhosemethod_missingcallssuper, sees only the first access of a name that gets an accessor. Move what the wrapper does to the code that reads the variable. -
Nginx::Connection,Nginx::ServerandNginx::Requestread their variables without callingNginx::Var: look for methods that a script defines onNginx::Var(class Nginx::Var,Nginx::Var.class_eval,define_method) and foriv_var, which the search above finds. A method ofNginx::Varno longer changes whatNginx::Connection#remote_ipand the other methods of the entry return; define the method on their class instead, inmruby_init_code, which runs once when nginx reads the configuration. Handler code runs on every request in the samemrb_state, so there the secondalias_methodwould makenginx_remote_ipa copy of the newremote_ip, which then calls itself:mruby_init_code 'class Nginx::Connectionalias_method :nginx_remote_ip, :remote_ipdef remote_ipNginx::Request.new.headers_in["X-Real-IP"] || nginx_remote_ip # works on bothendend'; -
Dircomes from mruby’s core gem, and a closedDirraisesIOErrorinstead ofRuntimeError: the search above findsRuntimeError; look at the ones that rescue an exception of aDirthat can be closed, or ofDir.openwith a block that closes theDir.d = Dir.open(path)d.closebegind.readrescue RuntimeError # 2.x: rescued 3.0.0: not rescued (IOError)endbegind.readrescue IOError, RuntimeError # rescued on bothend -
ENVcomes from mruby’s core gem:ENV.to_hashis gone, andENVisEnumerable,Processcomes from mruby’s core gem:Process.fork,Kernel#forkandKernel#systemare gone,exitin a handler raisesSystemExitinstead of ending the worker process,sleepwithout an argument raisesArgumentErrorand The default build leaves outVedisandCache(mruby-vedis and mruby-localmemcache): this finds the calls that change:grep -rnE 'to_hash|fork|system|to_int|Status\.new|exit!|(^|[^_.])exit|sleep *($|[;)}])|Vedis|Cache\.new' /path/to/scriptsENV.to_hash # 3.0.0: NoMethodErrorENV.to_h # 3.0.0: the Hash 2.x: NoMethodErrorENV.keys.each_with_object({}) { |k, h| h[k] = ENV[k] } # the Hash on bothexit # 2.x: ends the worker process 3.0.0: SystemExit, the handler answers 500Nginx.return Nginx::HTTP_SERVICE_UNAVAILABLE # 503 on both; the code then runs to its endsleep # 2.x: waits until a signal comes 3.0.0: ArgumentErrorStart other processes outside nginx instead of
forkandsystem, and keep the data ofVedisandCachein Redis or in a store of your own, or uncomment the gem’s line inbuild_config.rb. -
DigestandSecureRandomcome from gems of ngx_mruby that need OpenSSL 3.0 or later: this finds the calls whose result changes; look at thedupandcloneof digest objects, the HMAC objects whosedigestorhexdigestis called more than once, and theurlsafe_base64calls with an argument.grep -rnE 'Digest::|\.dup|\.clone|urlsafe_base64|random_bytes' /path/to/scriptsd = Digest::SHA256.new.update("ab")d.dup.update("c").hexdigest # 2.x: the SHA-256 of "c" 3.0.0: the SHA-256 of "abc"Digest::SHA256.new.update("c").hexdigest # the SHA-256 of "c" on bothSecureRandom.urlsafe_base64(32).size # 2.x: 22 3.0.0: 43SecureRandom.urlsafe_base64.size # 22 on both -
Nginx::Upstream#server=andNginx::Stream::Connection#upstream_server=raiseArgumentErrorfor a string that cannot be a server: the search above finds both setters andRuntimeError; look at the ones that rescue an exception of a setter.u = Nginx::Upstream.new "backend"beginu.server = "192.0.2.1:notaport"rescue RuntimeError # 2.x: rescued 3.0.0: not rescued (ArgumentError)endbeginu.server = "192.0.2.1:notaport"rescue ArgumentError, RuntimeError # rescued on bothend -
Nginx::Upstream#server=raisesArgumentErrorfor a host name instead of resolving it: the search above finds the setter; look at what the script gives it, also when the script reads the value from a request or a file.u.server = "localhost:8080" # 2.x: resolved while the worker waits 3.0.0: ArgumentErroru.server = "127.0.0.1:8080" # works on bothWrite an IPv4 address as four decimal numbers:
127.1raises as well. For a name that does not change while nginx runs, write it in theserverline of theupstream {}block and do not call the setter. nginx uses all the addresses of such a name: when it has more than one,Nginx::Upstream.newraisesRuntimeErrorfor that upstream, so remove that call too, or write an IP address in theserverline. A name that does not resolve stops nginx at start. -
The default build leaves out the auto-ssl mrbgem and the classes that came with it: this finds the constants and the two
Dirmethods that the default build no longer has:grep -rnE 'Nginx::SSL::ACME|Acme|HttpRequest|OpenSSL|PolarSSL|SimpleHttp|(^|[^:])HTTP::|Base64|Forwardable|FORWARDABLE|Tempfile|tmpdir' /path/to/scriptsBase64,Dir.tmpdirandDir.mktmpdirhave replacements in the default build:Base64.encode(s) # 3.0.0: NameError (uninitialized constant Base64)[s].pack('m0') # the same string on bothBase64.decode(b) # 3.0.0: NameErrorb.unpack1('m') # the same string on bothDir.tmpdir # 3.0.0: NoMethodErrorENV['TMPDIR'] || '/tmp' # works on bothFor
Dir.mktmpdir, see The auto-ssl mrbgem and the classes that came with it. The other constants need aconf.gemline of your own. -
An access or post_read handler that waits in
Nginx::Async.sleepends as without the wait: look forNginx::Async.sleepinmruby_access_handler*andmruby_post_read_handler*code. Undersatisfy any, an access handler that sleeps and then ends without a result now allows the request; one that should deny it returns the status after the sleep:Nginx::Async.sleep 100# 2.x: without a result, the request reached its content and the connection closed# 3.0.0: without a result, nginx allows the request under satisfy anyNginx.return Nginx::HTTP_FORBIDDEN unless allowed? # on both: denies under satisfy all; under satisfy any nginx tries the other access handlers -
An access or post_read handler that writes output ends the request after the response: nothing to change. Such a handler answers once and nginx keeps the connection, where 2.x went on with the phases and closed it; log alerts on its
header already sentlines no longer fire. -
A handler that sets no result does not take the result of an earlier handler: look for a server rewrite, rewrite, post_read or access handler that calls
Nginx.returnfor every request, for examplemruby_server_rewrite_handler_code 'Nginx.return Nginx::DECLINED'. The later content handlers that can end without output and without a status, and the access handlers undersatisfy anythat can end without a result, no longer take that value; one that should go on returns it itself:# mruby_content_handler_code, on a server whose server rewrite handler returns Nginx::DECLINEDNginx.rputs body if body # no body: 2.x went on to the static module 3.0.0 answers 200 with Content-Length: 0Nginx.return Nginx::DECLINED unless body # goes on to the static module on both -
An
mruby_sethandler that waits inNginx::Async.sleepsets its variable, and the request goes on: look forNginx::Async.sleepinmruby_setandmruby_set_code. Code that calledNginx.returnafter the sleep to end the request returns that status from a later handler, for example a rewrite handler that reads the variable. -
A rewrite or server rewrite handler that ends without a result goes on to the next phase handler: look at the
mruby_rewrite_handler*andmruby_server_rewrite_handler*handlers that can end withoutNginx.returnor withNginx.return Nginx::OK. On 2.x nginx ended such a request without a response; on 3.0.0 it goes on to the content of the location. A handler that should end the request returns the status it means:# mruby_rewrite_handler_codeNginx::Var.new.set "backend", "a" # no result: 2.x sends no response 3.0.0 goes onNginx.return Nginx::HTTP_FORBIDDEN if deny # 403 on both -
Nginx::Async::HTTP.sub_requestworks in a content handler, also afterNginx::Async.sleep: look for arescueofRuntimeErroraroundsub_requestinmruby_content_handler*code, and remove it; the call returns the response:Nginx::Async.sleep 100res = Nginx::Async::HTTP.sub_request "/backend" # 2.7.3: RuntimeError, 500 3.0.0: the responseNginx.rputs res.body -
A handler that waits for
Nginx::Async::HTTP.sub_requestruns its code once and ends as without the wait: nothing to change for most scripts. An access or post_read handler that callssub_requestruns once for the request on 3.0.0; work that counted on the code running again after the subrequest goes after the call, where its response is available. -
A UDP stream session runs its code once: datagrams that arrive while the code waits do not start it again: look for
Nginx::Stream::Async.sleepin the code oflisten ... udpservers. On 3.0.0 the code runs once for the session; datagrams that arrive during the sleep do not start it again. -
A stream session that waits when
worker_shutdown_timeoutexpires ends then: nothing to change; withworker_shutdown_timeout, a stream session whose code still sleeps when the timeout expires ends without the code after the sleep. -
Nginx.redirectwith a local URI takes effect when the handler ends: look forNginx.redirectwith a path in the handlers. On 3.0.0 the code after the call runs before the target; its output and its status are not sent, while the response headers that it sets and the arguments of the request that it changes reach the target:Nginx.redirect "/backend"Nginx.rputs "fallback" # 2.x: sent with the answer of /backend 3.0.0: not sent, warn linereturn # leave the handler when the code after the call should not run -
Nginx.rputs,Nginx.echo,Nginx.redirectandNginx::Filter#body=raiseTypeErrorwhento_sof the argument does not return a String: look for calls of these methods and ofNginx::Filter#outputwith an argument that is not a String, and pass a String,nilor a value whoseto_sreturns a String instead. -
Nginx::Async::HTTP.sub_requestraises aRuntimeErrorin anmruby_sethandler: look forNginx::Async::HTTP.sub_requestinmruby_setandmruby_set_code. Call it in a rewrite or access handler, which waits for the subrequest, and set the variable there withNginx::Var#set. -
An
mruby_setvalue that cannot be converted to a String answers 500: look formruby_setandmruby_set_codewhose code can return a value that is not a String, and return a String instead. -
Nginx.redirectwith a local URI raises aRuntimeErrorin a log handler: look forNginx.redirectwith a path in the code ofmruby_log_handlerandmruby_log_handler_code, and move the call to a rewrite, access or content handler. -
Output is sent with the status that the handler set, and
error_pagedoes not apply to it: look forNginx.return,Nginx.send_headerandNginx.status_code=before and afterNginx.rputsorNginx.echoin the handlers, and forerror_pagein the locations of those handlers. On 3.0.0 the output goes out with the status, and anerror_pagefor that status does not apply:# 2.x: nginx's 401 page, or the page of an error_page for 401 3.0.0: 401 with the JSONNginx.rputs '{"error":"no key"}'Nginx.return Nginx::HTTP_UNAUTHORIZEDWithout the
Nginx.rputs, both versions answer nginx’s 401 page or the page of theerror_page, so a handler that relied on them sets the status without output. After output, 301, 302, 303, 307 and 308 get noLocationunless the script sets it withNginx::Headers_out, and a status below 200 answers 500. A status set before the first output follows the same rule on 3.0.0, where 2.x sent the output with 200: a handler that means 200 callsNginx.return Nginx::HTTP_OKafter the output.Nginx::HTTP_CLOSE(444) with output, before or after it, sends nothing and closes the connection, as 2.x does for 444 after the output; 2.x sent output written after 444 with 200. -
Methods that have no effect in a handler raise a
RuntimeErrorthere: look in the code ofmruby_log_handler*,mruby_output_header_filter*,mruby_output_body_filter*,mruby_setandmruby_set_codefor the methods of the rows below whose handler is in the third column, and forNginx::Filter#bodyoutside a body filter. On 3.0.0 each such call raises aRuntimeErrorthat names the method and the handler, where 2.x returned without an effect on the response. Remove the call, or move it to a handler of the second column.Methods Where they work New raise Reading the request: the getters of Nginx::Request,Nginx::Headers_in#[], the reads ofNginx::Var,Nginx::Connection, the getters ofNginx::Serverevery handler and filter of a request none Changing the request: uri=,args=,method=,request_line=,Nginx::Headers_in#[]=and#deletemruby_sethandlers, the post_read, server rewrite, rewrite, access and content handlerslog handlers, header and body filters Assigning variables: Nginx::Var#NAME=,#setevery handler and filter of a request none The response head: Nginx::Headers_out#[]=and#delete,Nginx.status_code=,Nginx.returnandNginx.send_headerwith a status,content_type=every handler and filter of a request but a log handler, while nginx has not sent the response header log handlers, and the other handlers after the response header is sent Output: Nginx.rputs,Nginx.echothe post_read, server rewrite, rewrite, access and content handlers, and body filters mruby_sethandlers, log handlers, header filtersThe body of a body filter: Nginx::Filter#body,#body=,#outputbody filters #bodyelsewhere (#body=and#outputraised there before)A log handler that passes a value to
access_logassigns a variable withNginx::Var, which works there:# in mruby_log_handler_codeNginx::Request.new.headers_out["X-Cost"] = cost # 2.x: no effect 3.0.0: RuntimeErrorNginx::Var.new.cost = cost.to_s # both: access_log writes $cost -
Nginx.redirectwith a local URI raises aRuntimeErrorinmruby_sethandlers and output filters: look forNginx.redirectwith a path in the code ofmruby_set,mruby_set_code,mruby_output_header_filter*andmruby_output_body_filter*. On 3.0.0 the call raises aRuntimeErrorand makes no internal redirect, where 2.x ran the handlers of the other location inside the call. Move the call to a rewrite or access handler, where the redirect takes effect when the handler ends:# in mruby_set_code: 2.x: the redirect runs inside the call 3.0.0: RuntimeError, the variable is emptyNginx.redirect "/backend"# in mruby_rewrite_handler_code: the redirect takes effect when the handler ends, on 3.0.0Nginx.redirect "/backend" -
Assigning a variable that nginx does not know, or does not let scripts change, raises: look for assignments with
Nginx::Var(v.<name> =andset), and for theerrorlinesis not found,not changeableandis not assingedofngx_mrb_var_set_vectorandngx_mrb_var_set_funcin theerror.logof a 2.x server, which name the variables that such an assignment missed. On 3.0.0 the assignment raisesNameErrorfor a name that nginx does not know andRuntimeErrorfor a variable that nginx does not let scripts change, or keeps no value of, where 2.x logged the line, returnedniland went on. Declare the variable withsetormruby_variable, or change the request with the setters ofNginx::RequestandNginx::Headers_in:v = Nginx::Var.newv.backend_url = "http://10.0.0.2/" # no set or mruby_variable declares $backend_url: 2.x: nil and an error line 3.0.0: NameErrorv.uri = "/other" # 2.x: nil and an error line 3.0.0: RuntimeErrorNginx::Request.new.uri = "/other" # changes the URI on both
Dir.children, Dir#each_child, Dir.empty? and the methods of
Enumerable on a Dir are new to scripts of 2.x; the first two leave out
. and .. (see New features).
Log monitoring
Section titled “Log monitoring”-
Exception#inspect, and so themrb_run failedlines oferror.log, use a new format: look in log parsers and alert rules for patterns onmrb_run failedlines, and for an exception class in parentheses at the end of a line.2.x: mrb_run failed: return 500 HTTP status code to client: error: boom (RuntimeError)3.0.0: mrb_run failed: return 500 HTTP status code to client: error: #<RuntimeError: boom>A pattern such as
\(RuntimeError\)$becomes#<RuntimeError:. -
The message of
NoMethodErrornames the class of the receiver: a pattern that ends atundefined method 'foo'no longer matches, because the message goes on withfor <class>. -
The messages logged while nginx reads the configuration are at the
infolevel instead ofnotice: look in log parsers, alert rules and start scripts formechanism enabled,compile info,target variableandngx_mruby NOTICE. A start of nginx no longer writes these lines.nginx -twrites them at[info]to the startup log, which is the file given with-e, or else the error log path compiled into nginx (logs/error.logunder the prefix by default). nginx copies a line of the startup log to the terminal only atwarnand above, so the output ofnginx -tdoes not show them.2.x, start: [notice] ... ngx_mruby/<version> (mruby/3.3.0) mechanism enabled in ...3.0.0, start: no such line3.0.0, nginx -t: [info] ... ngx_mruby/<version> (mruby/4.1.0) mechanism enabled in ... (startup log only)3.0.0, nginx -t -e stderr: [info] ... ngx_mruby/<version> (mruby/4.1.0) mechanism enabled in ... (terminal)A check that looks for one of these lines to see that the module is loaded runs
nginx -t -e stderrand reads its output, or reads the startup log afternginx -t:nginx -t -e stderr 2>&1 | grep 'mechanism enabled' -
Nginx.module_versionand themechanism enabledline give 3.0.0: look in scripts forNginx.module_version, and in log parsers and alert rules for patterns on the version afterngx_mruby/. A comparison with a 2.x version, such as2.7.1, or a pattern such asngx_mruby/2\.no longer matches: 3.0.0 and its pre-releases give3.0.0. -
Syntax errors have the messages of Prism: a pattern on the text after
syntax error, such asunexpected end of file, no longer matches. Match onSyntaxErrorand on the file and line instead.2.x: file (eval) line 1: syntax error, unexpected end of file3.0.0: file (eval) line 1: syntax error, unexpected end-of-input; expected an expression after the operator -
A content handler that ends without output answers 200 with an empty body instead of 500: a pattern on
response body is empty. return NGX_HTTP_INTERNAL_SERVER_ERRORno longer matches for the content handlers of the main request that end without output and with no status or a status from 200 to 299 that nginx does not answer by itself; it still matches for a status below 200, and forNginx::HTTP_OKwithout output in the other handlers and in subrequests. -
An output body filter that ends with an empty body sends the response instead of closing the connection: an alert on
zero size buf in writerno longer fires for these responses, because nginx sends them. -
access_logwrites the variables that mruby log handlers set, and the status that was sent: find themruby_log_handlerandmruby_log_handler_codedirectives, the variables that their code assigns withNginx::Var(v.NAME = ...andv.set "NAME", ...), and thelog_formatlines that name those variables. These lines now have the value that the log handler assigned, not the value from before it. A line that should keep the value from before the log handler names a copy thatsetmakes in the location, which runs before the log phase:set $tokens "-";set $tokens_before_log $tokens;The status in the access log line is the status that was sent, also after a log handler raised; its
mrb_run failedline still goes toerror.log.
C extensions and mrbgems
Section titled “C extensions and mrbgems”This finds the places in the C sources of a gem, or of a program that embeds mruby, that the entries below are about:
grep -rnE 'Data_Wrap_Struct|mrb_data_object_alloc|MRB_SET_INSTANCE_TT|MRB_ARGS_|mruby/ext/io\.h|mrb_alloca|mrb_open|allocf|MRB_NO_PRESYM' src/-
An object of a class not declared
MRB_TT_DATAcannot wrap C data: every class whose objectsData_Wrap_Structormrb_data_object_alloccreates needs the declaration aftermrb_define_class:struct RClass *c = mrb_define_class(mrb, "Uname", mrb->object_class);MRB_SET_INSTANCE_TT(c, MRB_TT_DATA); -
mruby checks the argument count of a C method against its spec: compare the spec of each
mrb_define_methodwith what itsmrb_get_argsreads, in both directions. A method defined withMRB_ARGS_REQ(2)that reads one string (mrb_get_args(mrb, "S", &s)) and is called with one argument raisesArgumentError; define it withMRB_ARGS_REQ(1). A method defined withMRB_ARGS_REQ(1)that reads"o|o"and is called with two arguments raises too; define it withMRB_ARGS_ARG(1, 1). -
Renamed headers and functions, and
mrb_open()on failure:#include <mruby/io.h> /* was <mruby/ext/io.h> */void *buf = mrb_temp_alloc(mrb, size); /* was mrb_alloca(mrb, size) */mrb_state *mrb = mrb_open(); /* also in place of mrb_open_allocf(my_allocf, ud) */if (MRB_OPEN_FAILURE(mrb)) { /* ... */ } /* was: if (mrb == NULL) *//* a custom allocator, in place of mrb_default_allocf() or my_allocf */void *mrb_basic_alloc_func(void *ptr, size_t size) { /* ... */ } -
Sources that include
mruby.hneed the generated headers: add-I<mruby>/build/host/includenext to-I<mruby>/includewhere you compile such a source outside the mruby build.
Checking the result
Section titled “Checking the result”-
Compile every script with the
mrbcof mruby 4.1.0-rc2. After a build of this release (sh build.shorsh test.sh),mruby/bin/mrbc -cchecks the syntax of a script: it printsSyntax OK, or the line of the error (for a constant assigned in a method body,<file>:2:3: syntax error, dynamic constant assignment) and exits with 1.for f in /path/to/scripts/*.rb; do mruby/bin/mrbc -c "$f" || echo "check: $f"; done -
Run the parts of a script that do not call the
Nginxclasses with both versions of mruby. The entries of mruby 4.0.0 were measured this way between 2026-10-04 and 2026-10-14: the same Ruby script ran with twomrubybinaries, one built from the mruby tree of ngx_mruby 2.x (mruby 3.3.0) and one from mruby 4.0.0, in Docker (Ubuntu 22.04, gcc 11), with mruby’sdefaultgembox or with the core gems of each version’s ngx_mruby build (full-coreand iij/mruby-dir for 3.3.0,NGX_MRUBY_CORE_GEMSfor 4.0.0). The entries of mruby 4.1.0-rc2 were measured on 2026-10-29 and 2026-10-31 with themrubycommand of the host build of ngx_mruby, for 4.0.0 and for 4.1.0-rc2, and with themrubycommand of mruby 3.3.0 built with itsdefaultgembox. The entries that say “the test suite of ngx_mruby saw the change” also changed a response or a log line of ngx_mruby itself. To do the same, copy themruby/directory of each version to a directory of its own, runrake MRUBY_CONFIG=defaultin each copy, and run your script with thebin/mrubyof both copies. Do not run that rake in themruby/of an ngx_mruby checkout: it builds intomruby/build, where the build of the module keeps its mruby. -
Run the configuration with the module of this release on a test server, send the requests that reach each handler, and look in
error.logformrb_run failedlines withNoMethodError,TypeError,ArgumentErrororSyntaxError.
These were checked the same way and did not change, so they need no check:
String#size and #length count bytes (the mruby-encoding gem is not in
the default build; see Core gems); the
ArgumentError for a wrong number of arguments; Exception#message;
Struct#inspect; Float#to_s; Integer division and modulo; Kernel#sleep
and #usleep (from mruby-sleep).