Skip to content

🎯 Simple rule-based redirecting from one URL to another.

License

Notifications You must be signed in to change notification settings

TomerAberbach/redirect-url

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

redirect-url

Simple rule-based redirecting from one URL to another.

Features

Install

$ npm i redirect-url

Usage

import { createRedirectUrl, parseRedirectUrl } from 'redirect-url'

let redirectUrl = createRedirectUrl([
  // Nice :)
  [`/bliss`, `https://www.youtube.com/watch?v=dQw4w9WgXcQ`],

  // Other redirects...
  { from: `/home`, to: `/`, status: 307 },
  [`/:splat*\\.html`, `/:splat*`],
])
// OR
redirectUrl = parseRedirectUrl(`
  # Nice :)
  /bliss            https://www.youtube.com/watch?v=dQw4w9WgXcQ

  # Other redirects...
  /home             /          307
  /:splat*\\.html   /:splat*
`)

console.log(redirectUrl(`https://example.com/bliss`))
//=> { url: 'https://www.youtube.com/watch?v=dQw4w9WgXcQ', status: 302 }
console.log(redirectUrl(`https://example.com/home`))
//=> { url: 'https://example.com', status: 307 }
console.log(redirectUrl(`https://example.com/about-me.html`))
//=> { url: 'https://example.com/about-me', status: 302 }
console.log(redirectUrl(`https://example.com/spaghetti`))
//=> null

This package can be used with any server or framework, but see some example integrations below. Feel free to send pull requests for more examples!

Express

const redirectsMiddleware = (req, res, next) => {
  const result = redirectUrl(req.url)
  if (result) {
    res.redirect(result.status, result.url)
  }
  next()
}

app.all(`*`, redirectsMiddleware)

Remix

entry.server:

const handleRequest = request => {
  const result = redirectUrl(request.url)
  if (result) {
    return redirect(result.url, result.status)
  }

  // ...
}

export default handleRequest

API

See here!

Contributing

Stars are always welcome!

For bugs and feature requests, please create an issue.

For pull requests, please read the contributing guidelines.

License

Apache License 2.0

This is not an official Google product.