Jump to content

Manual talk:$wgFileCacheDepth

Add topic
From mediawiki.org
Latest comment: 11 years ago by Superxain in topic Serving pages directly through nginx

Serving pages directly through nginx

[edit]

Inspired by the Apache tutorial, I've managed to write a small script to serve cached files directly through nginx. It works well, it is very fast and it falls back to MediaWiki if the files don't exist.

Since the nginx configuration language is pretty limited (it doesn't allow nested if statements, for example), I did it in Lua. It requires the ngx_lua module.

The following conf should be integrated inside your server block, and it assumes that:

  • you're using fancy urls like example.com/Page;
  • your cache folder is inside your MediaWiki folder (default);
  • you're already proxying *.php files to php-fpm (or whatever) in the last location block.

And here are the limitations:

  • as with the Apache solution, you have to run a cron job or manually rebuild the cache files when they change;
  • pages whose title include non-ASCII characters are served through PHP (which should be transparent to the user anyway).

Change paths as needed.

location ~ /cache/(.*) {
    internal;
}

location / {
    default_type 'text/html';
    rewrite_by_lua '
        local cookie = ngx.req.get_headers()["Cookie"] or ""
        if string.match(cookie, "UserID") then  -- if we are logged in...
            ngx.exec("@rewrite")
        else
            local page = string.sub(ngx.var.request_uri, 2, -1)  -- get the page name without the leading slash
            local filename = page .. ".html"
            local f = io.open("/var/www/w/cache/" .. filename, "r")
            if f ~= nil then  -- if the file exists, close it and serve it directly
                io.close(f)
                ngx.header["x-wiki-cache"] = "via nginx"  -- headers to help you debug
                ngx.exec("/cache/" .. filename)
            else
                ngx.header["x-wiki-cache"] = "via mediawiki"
                ngx.exec("@rewrite")
            end
        end
    ';
}
 
location @rewrite {
    rewrite ^/([^?]*)(?:\?(.*))? /index.php?title=$1&$2 last;
}

--Gika (talk) 17:34, 25 May 2013 (UTC)Reply

great tip. I think this should add to Manual:File_cache page. --Superxain (talk) 12:28, 29 July 2013 (UTC)Reply