I recently came across a requirement to implement something like Overlay FS with NGINX when deploying MediaWiki. Specifically, I was using the Git version of MediaWiki and needed to add some custom files to the directory (such as logos,
favicon.ico, various verification files, etc.). I wanted to keep these files separate from the source code in order not to pollute Git and to reduce the hassle when upgrading.
To abstract the problem, NGINX needed to serve from
/srv/foo/orig, and now it needs to additionally try to search for files from
/srv/foo/overlay in addition to the original path (note that unlike Overlay FS, the original path is used first). And since MediaWiki relies on PHP, it also needs to be able to handle both dynamic and static files.
After several fumbling sessions, I obtained the following configuration.
With these configurations, NGINX will try the following in order when it encounters a path shaped like
- go to
- go to
@orig: rewrite the query string as
/index.phpand have FastCGI process the request. This part is suitable for cases where no static file is matched in either location, and any underhanded operation can be performed, such as leaving it to a dynamic program, redirecting it (
rewrite), or returning an error (
error_page). Note that this section cannot be merged into
rootof the two is different.
@orig above are named locations for NGINX, described in the official documentation as follows.
The “@” prefix defines a named location. Such a location is not used for a regular request processing, but instead used for request redirection. They cannot be nested, and cannot contain nested locations.
One of the advantages of using named location is that the jump does not affect the actual URL and avoids all kinds of complicated matching processing. Note that you must use
@overlay to switch directories, because you cannot use
alias in named location. Also, due to some mechanism I haven’t figured out yet (related to the NGINX context), the configuration must cascade
try_files for chaining, not
try_files $uri $uri/ @overlay @orig.
If there are only static files, then just keep
@overlay. If you want to search the overlay directory first (same usage as Overlay FS), you need to write it differently.
root is the same, here
@orig_dyn is merged directly into