I am using Nginx njs module for some url modifications.
My use case is to return the redirection uri for the given uri.
URI's will be as follows:
/books
/books/economic-genious
/books/flight-mechanics
My regular expression to match the above URI's as follows -
/books/(.*)|/books$
First part of expression /books/(.*)
is to match below URI's:
/books/economic-genious
/books/flight-mechanics
Second part of expression /books$
is to match below URI's:
/books
My destination is configured as follows: /ebooks/$1
. So that the above URI's will be converted to:
/ebooks
/ebooks/economic-genious
/ebooks/flight-mechanics
Javascript code:
function getMappedURI(uri) {
var exp = new RegExp('/books/(.*)|/books$');
var destUri = '/ebooks/$1';
var redirectUri = uri.replace(exp, destUri);
return redirectUri;
}
Above code is working fine for the below URI's:
/books/economic-genious
/books/flight-mechanics
But for the URI /books
, it should return /ebooks/
. But it is appending some non printable special character at the end of /ebooks/
.
I think it is trying to replace $1
with some special character.
How to avoid adding of special character at the end ?
Try with this regex: \/books(\/(.*))?$
Demo here...
code:
function getMappedURI(uri) {
var exp = new RegExp('\/books(\/(.*))?$');
var destUri = '/ebooks$1';
var redirectUri = uri.replace(exp, destUri);
return redirectUri;
}