How to serve files from memory with a fallback using nginx

Serve files from memory with a fallback using nginx HTTP server.

The goal is to serve files from memory using tmpfs filesystem mounted at /var/www/tmpfs/ directory and use a fallback /var/www/html/ directory in case the requested file or direcory is missing.

Install nginx HTTP server.

$ sudo apt-get install nginx-full

Create directory for tmpfs.

$ sudo mkdir -p /var/www/tmpfs

Mount tmpfs filesystem.

$ sudo mount -t tmpfs -o rw,nodev,nosuid,noexec,size=128M tmpfs /var/www/tmpfs/

Ensure that it will be mounted on boot.

$ echo "tmpfs /var/www/tmpfs tmpfs rw,nodev,nosuid,noexec,size=128M 0 0" | sudo tee -a /etc/fstab 

Disable default virtual host configuration.

$ sudo unlink /etc/nginx/sites-enabled/default

Prepare virtual host configuration.

$ cat << EOF | sudo tee /etc/nginx/sites-available/default-tmpfs-with-fallback
server {
  listen 80 default_server;
  listen [::]:80 default_server;
  index index.html index.htm index.nginx-debian.html;

  server_name _;

  location / {
    root /var/www/tmpfs/;
    try_files \$uri \$uri/ @fallback;
  }

  location @fallback  {
    root /var/www/html/;
    try_files \$uri \$uri/ =404;
  }
}
EOF
server {
  listen 80 default_server;
  listen [::]:80 default_server;
  index index.html index.htm index.nginx-debian.html;

  server_name _;

  location / {
    root /var/www/tmpfs/;
    try_files $uri $uri/ @fallback;
  }

  location @fallback  {
    root /var/www/html/;
    try_files $uri $uri/ =404;
  }
}

Enable this virtual host.

$ sudo ln -s /etc/nginx/sites-available/default-tmpfs-with-fallback /etc/nginx/sites-enabled/

Verify configuration syntax.

$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

Reload HTTP server configuration.

$ sudo systemctl reload nginx

Install rsync a fast, versatile, remote (and local) file-copying tool.

$ sudo apt-get install rsync

Copy website to tmpfs filesystem.

$ sudo rsync --archive /var/www/html/ /var/www/tmpfs/

Done.

About Milosz Galazka

Milosz is a Linux Foundation Certified Engineer working for a successful Polish company as a system administrator and a long time supporter of Free Software Foundation and Debian operating system.