GithubHelp home page GithubHelp logo

codewithkristian / lilredirector Goto Github PK

View Code? Open in Web Editor NEW
128.0 4.0 19.0 466 KB

๐Ÿ”Œโšก๏ธ Redirector engine built for Cloudflare Workers

License: Apache License 2.0

TypeScript 100.00%

lilredirector's Introduction

banner

A simple (but powerful!) redirect tool built with Cloudflare Workers. Deploy and manage redirects at the edge without needing to config your origin application.

demo

Installation

This project requires the usage of Cloudflare Workers on your custom domain/zone. Check out my Egghead video on deploying to a custom domain if you need to set that up.

With a configured Workers project, using Wrangler:

  1. Install the package
$ npm install lilredirector
  1. Create a redirects.js file in your source code:
export default [
  {
    path: "/twitter",
    redirect: "https://twitter.com/signalnerve",
  },
  {
    path: "/yt",
    redirect: "https://www.youtube.com/c/bytesizedxyz",
  },
]

Usage

import redirector from 'lilredirector'
import redirects from './redirects'

addEventListener('fetch', event => event.respondWith(handler(event)))

// Note the `event` function argument. 
// Unlike many Workers scripts, which pass in `event.request`, 
// lilredirector needs the full `event` object
async function handler(event) {
  const { response, error } = await redirector(event, redirects)
  if (response) return response

  // Optionally, return an error response
  if (error) return error

  // Other workers code
}

Path parameters

Lilredirector includes support for more complex redirect scenarios using path parameters. This allows you to capture parameters in the URL and use it to route to new URLs. In redirects.js:

export default [
  {
    path: "/post/:id",
    redirect: "/posts/:id"
  },
  {
    path: "/users/:id/posts/:post_id",
    redirect: "/u/:id/p/:post_id"
  },
]

Configuration

import redirector from 'lilredirector'

addEventListener('fetch', event => event.respondWith(handler(event)))

async function handler(event) {
  const { response, error } = await redirector(event, redirects, {
    // Configuration options can be passed as an optional object.
    // See the below documentation for examples of each:
    //
    // baseUrl
    // basicAuthentication
    // removeTrailingSlashes
  })
  // ...
}

Changing the base URL

By default, lilredirector serves a read-only UI from /_redirects. This can be customized by providing baseUrl in lilredirector's configuration:

async function handler(event) {
  const { response, error } = await redirector(event, redirects,{
    baseUrl: `/mylilredirector`,
  })
  if (response) return response
}

Removing trailing slashes

By default, lilredirector will match and redirect URLs without trailing slashes. For instance, if you have a redirect set up for /about, visiting /about/ will match a redirect for /about, and redirect accordingly. This feature can be disabled by passing the removeTrailingSlashes boolean in the configuration object into the redirector function:

async function handler(event) {
  const { response, error } = await redirector(event, redirects, {
    removeTrailingSlashes: false,
  })
  if (response) return response
}

How it works

Handlers

Lilredirector embeds itself under the /_redirects path, unless specified otherwise by the baseUrl configuration param as defined in the previous section.

Authentication

You can put the read-only UI behind authentication using a few methods.

Basic authentication

Using the configuration object, you can enable basic auth for lilredirector and any subpaths (creating/deleting redirects):

async function handler(event) {
  const { response, error } = await redirector(event, redirects, {
    basicAuthentication: {
      username: USERNAME,
      password: PASSWORD,
    },
  })
  if (response) return response
}

It's strongly recommended that you use wrangler secret to define and store your basic auth credentials, as seen above:

$ wrangler secret put USERNAME
$ wrangler secret put PASSWORD

Cloudflare Access

You can add complex role-based auth using cloudflare access. see the below screenshot for an example config:

access setup

lilredirector's People

Contributors

adamschwartz avatar codewithkristian avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

lilredirector's Issues

Version 1.0: Move to file-based redirect storage

Currently lilredirector is based on Workers KV storage. This is an interesting and useful look at how quick it can be to spin something up with KV, but it leaves a lot to be desired in a number of ways when it comes to practically and efficiently using lilredirector at scale:

  1. Lots of manual configuration that requires intermediate+ understanding of Workers and Wrangler (setting up a KV namespace, adding it to wrangler.toml, etc)
  2. No tracking of when a redirect was added, or by whom
  3. View counts are useful but inaccurate with KV as it stands -- Durable Objects can fix this but isn't necessarily any better at issues 1 or 2

Moving to a file-based system, e.g. loading in JSON or something similar, will mitigate the above issues. A file can be tracked via Git, easily moved between environments (e.g. in development or production), and will have minimal impact on file size for most situations.

In version 1.0, lilredirector will load redirects from a file as the Worker boots up. This will likely make it easier to support more advanced configuration as well (e.g. regex support as requested in #10), and remove a ton of code for managing the UI and associated API routes for managing these redirects at the edge.

Note that this is like..... a really breaking change. In addition, I'll need to spend some time specifying what the file looks like -- for instance, is it JSON? TOML? YAML? There's a ton of things to figure out here, but in case anyone is interested in the long-term direction of this project, I wanted to document some of this stuff and make it available for discussion.

Side note: there's been some discussion in the Workers discord re: text bindings, which are used for the static asset manifest. Because they aren't supported by Wrangler, I don't think it's the right direction right now, though there's definitely an argument to be made that since we're using something very similar for Workers Sites (using text bindings to map paths to known filenames), it could probably be a good fit here as well. I'd revisit this as an option in the future if Wrangler supports easy management of those values.

bulk adding

should be able to enter CSV-style values into a textarea and bulk upload redirects

Support Regex

Regex support would be great, so you can do things like this:

/product1/* -> new product1 url.

Even a starts-with type regex would be helpful.

There may be also times it would be helpful to have intermediate wildcards for things like locales.

I understand this isn't feasible with the current way you are handling the query/storage of redirects in KV... but maybe it's worth looking at changing that?

Instead of Key-per-entry, you could do everything in one key and then filter it?

trim form inputs

when adding a path or redirect, the form input should be trimmed in case there are extra spaces. just did this in production, yikes!

Add time-limited redirects

Sometimes redirects are not permanent, and they need to be enabled or disabled at specific times.

It would be nice to be able to specify a start date and end date for redirects which automatically get respected in the worker by comparing to current time.

validate URLs that are being entered

do a URL check before setting the value in KV - if it 404s, we should reject it (maybe a bad URL).

this should be able to be disabled in config (what if someone is pre-adding URLs that aren't available yet) but seems like a sane default

if using Cloudflare Access, verify the tls

In order to expose the redirects UI by mistake by moving to different (sub)domain, what about adding something like cfaccess: true settings and make sure the cf.tlsClientAuth is present/verified?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.