Los Angeles v0.3

URL Rules

In addition to the page server features, Los Angeles includes a simple URL rewrite, redirect and proxy feature.

Setup

To setup the URL mapping use the urlRules() method of the Los Angeles component which returns an Express middleware:

// Load LosAngeles
const la  = require('@toptensoftware/losangeles');

// Run redirect rules
app.use(la.urlRules([
    // redirect rules go here (see below)
]));

Configuring Rules

The urlRules() method expects an array of rules that should be processed.

Each entry in the array is a JavaScript object with either a redirect, rewrite or proxy field declaring a regular expression to match against the URL and a to property specifying where the URL should be remapped:

[
    // Redirect
    { 
        redirect: /^\/downloads\/(.*)$/i, 
        to: "http://static.mysite.com/$1" 
    },

    // Rewrite 
    { 
        rewrite: /^\/downloads\/(.*)$/i, 
        to: "/newblog/$1" 
    },

    // proxy
    { 
        proxy: /^\/myproduct\/releasenotes.json/i, 
        to: "http://static.mysite.com/myproduct-releaseNotes.json" 
    }
]

Unless Exists Rules

To create a rule that only takes effect if a file doesn't exist, add an unless property.

These can be used to create fallback's for statically hosted single page apps.

When present the redirect/rewrite will take effect if the file indicated by unless doesn't exist. Use $n for captured matches in the orginal URL.

eg: the following rule will redirect a URL like /someapp/somepath/tail to /someapp/index.html... unless the file at /someapp/somepath/tail exists.

[
    // SPA rewrite
    {
        rewrite: /^\/someapp\/(.*)$/,
        to: "/someapp/index.html",
        unless: "./someapp/$1",
    },
]

If the resulting unless file is a relative path it will be resolved against the path given by baseDir in the options object passed as the second parameter to the urlRules function.

// Redirect rules with a base directory for resolving `unless` redirect/rewrites.
app.use(la.urlRules(require('./redirects'), {
    baseDir: path.join(__basedir, "public),
}));