Skip to content

How to rewrite URLs to local or remote destinations

Lloyd Brookes edited this page Jun 24, 2019 · 17 revisions

Local targets

Your application requested /css/style.css but you'd like to serve /css/new-theme.css instead. The syntax is:

$ ws --rewrite '<source route> -> <destination route>'

For example.

$ ws --rewrite '/css/style.css -> /css/new-theme.css'

Re-route any stylesheet under /css/ to /build/css/. Routes are specified using path-to-regexp v3 routing syntax. This syntax is virtually identical to Express v4 routing syntax except for wildcard expressions, which should be written as (.*) instead of *.

$ ws --rewrite '/css/:stylesheet -> /build/css/:stylesheet'

Re-route the entire directory structure under /css/ to /build/css/ (this rewrites /css/a as /build/css/a, /css/a/b/c as /build/css/a/b/c etc.). In the replace expression, use $1, $2 etc to replace each matched group.

$ ws --rewrite '/css/(.*) -> /build/css/$1'

Remote targets

If the to URL contains a remote host, local-web-server will act as a proxy fetching and responding with the remote resource.

Mount the npm registry locally:

$ ws --rewrite '/npm/(.*) -> http://registry.npmjs.org/$1'

Map local requests for repo data to the Github API:

$ ws --rewrite '/:user/repos/:name -> https://api.github.com/repos/:user/:name'

Multiple rules

To specify multiple rules on the command line you can supply either a list of values:

$ ws --rewrite '.xhtml -> .html' '/posts/:id -> /data/:id.json'

Or set the --rewrite option multiple times. Both have the same effect.

$ ws --rewrite '.xhtml -> .html' --log.format stats --rewrite '/posts/:id -> /data/:id.json'

Usage in stored config

Rewrite rules should be stored in the config file as an array of { from: string, to: string } objects.

module.exports = {
  rewrite: [
    { from: "/css/(.*)", "to": "/build/styles/$1" },
    { from: "/npm/(.*)", "to": "http://registry.npmjs.org/$1" },
    { from: "/broken/(.*)", "to": "http://localhost:9999" },
    { from: "/:user/repos/:name", "to": "https://api.github.com/repos/:user/:name" }
  ]
}

Debugging

To filter the verbose output to show only rewrite activity, set --verbose.include middleware.rewrite.

$ ws --rewrite '/posts/:id -> /data/:id.json' --verbose.include middleware.rewrite
{
  'middleware.rewrite.config': { rewrite: [ { from: '/posts/:id', to: '/data/:id.json' } ] }
}

Now, when you make requests e.g...

$ curl http://127.0.0.1:8000/posts/10

...you will see a JSON stream of debug information output from the server.

{
  'middleware.rewrite.local': { from: '/posts/10', to: '/data/10.json' }
}
Clone this wiki locally