[Fixed] How can I allow slashes in my Express routes?


I’m attempting to implement permalinks, in the form /2013/02/16/title-with-hyphens. I’d like to use route parameters. If I try the following route:

app.get('/:href', function(req, res) { });

…then I get a 404, presumably because Express is only looking for one parameter, and thinks that there are 4.

I can work around it with /:y/:m/:d/:t, but this forces my permalinks to be of that form permanently.

How do I get route parameters to include slashes?


Use a regular expression instead of a string.

app.get(/^\/(.+)/, function(req, res) {
    var href = req.params[0]; // regexp's numbered capture group

Note that you cannot use the string syntax (app.get('/:href(.+)')) because Express only allows a small subset of regular expressions in route strings, and it uses those regular expressions as a conditional check for that particular component of the route. It does not capture the matched content in the conditional, nor does it allow you to match across components (parts of the URL separated by slashes).

For example:


This route only matches if the first component (compa) is a single digit, and the second component (compb) is a single letter a-z.

'/:href(.+)' says “match the first component only if the content is anything”, which doesn’t make much sense; that’s the default behavior anyway. Additionally, if you examine the source, you’ll see that Express is actually forcing the dot in that conditional to be literal.

For example, app.get('/:href(.+)') actually compiles into:


Notice that your . was escaped, so this route will only match one or more periods.

Leave a Reply

(*) Required, Your email will not be published