Code Monkey home page Code Monkey logo

redirect-module's Introduction

Redirect Module πŸ”€ No more cumbersome redirects!

npm version npm downloads Circle CI Codecov Dependencies Standard JS

Nuxt 2 module to dynamically redirect initial requests

πŸ“– Release Notes

Nuxt 3

In Nuxt 3 redirects are supported out of the box through Route Rules, this module may not be needed.

export default defineNuxtConfig({
  routeRules: {
   // Redirects legacy urls
    '/old-page': { redirect: '/new-page' }
  }
})

Features

Redirecting URLs is an often discussed topic, especially when it comes to SEO. Previously it was hard to create a "real" redirect without performance loss or incorrect handling. But this time is over!

Setup

  1. Add the @nuxtjs/redirect-module dependency with yarn or npm to your project
  2. Add @nuxtjs/redirect-module to the modules section of nuxt.config.js:
  3. Configure it:
{
  modules: [
    ['@nuxtjs/redirect-module', {
      // Redirect option here
    }]
  ]
}

Using top level options

{
  modules: [
    '@nuxtjs/redirect-module'
  ],
  redirect: [
    // Redirect options here
  ]
}

Options

rules

  • Default: []

Rules of your redirects.

onDecode

  • Default: (req, res, next) => decodeURI(req.url)

You can set decode.

onDecodeError

  • Default: (error, req, res, next) => next(error)

You can set callback when there is an error in the decode.

statusCode

  • Default: 302

You can set the default statusCode which gets used when no statusCode is defined on the rule itself.

Usage

Simply add the links you want to redirect as objects to the module option array:

redirect: [
  { from: '^/myoldurl', to: '/mynewurl' }
]

You can set up a custom status code as well. By default, it's 302!

redirect: [
  { from: '^/myoldurl', to: '/mynewurl', statusCode: 301 }
]

As you may have already noticed, we are leveraging the benefits of Regular Expressions. Hence, you can fully customize your redirects.

redirect: [
  { from: '^/myoldurl/(.*)$', to: '/comeallhere' }, // Many urls to one
  { from: '^/anotherold/(.*)$', to: '/new/$1' } // One to one mapping
]

Furthermore you can use a function to create your to url as well πŸ‘ The from rule and the req of the middleware will be provided as arguments. The function can also be async!

redirect: [
  {
    from: '^/someUrlHere/(.*)$',
    to: (from, req) => {
      const param = req.url.match(/functionAsync\/(.*)$/)[1]
      return `/posts/${param}`
    }
  }
]

And if you really need more power... okay! You can also use a factory function to generate your redirects:

redirect: async () => {
  const someThings = await axios.get("/myApi") // It'll wait!
  return someThings.map(coolTransformFunction)
}

Now, if you want to customize your redirects, how your decode is done or when there is some error in the decode, you can also:

redirect: {
  rules: [
    { from: '^/myoldurl', to: '/mynewurl' }
  ],
  onDecode: (req, res, next) => decodeURI(req.url),
  onDecodeError: (error, req, res, next) => next(error)
}

ATTENTION: The factory function must return an array with redirect objects (as seen above).

Gotchas

The redirect module will not work in combination with nuxt generate. Redirects are realized through a server middleware, which can only react when there is a server running.

Development

  1. Clone this repository
  2. Install dependencies using yarn install or npm install
  3. Start development server using npm run dev

License

MIT License

Copyright (c) Alexander Lichter [email protected]

redirect-module's People

Contributors

alex61nn5 avatar derz avatar harlan-zw avatar jengel3 avatar juno-yu avatar mannil avatar rchl avatar renovate[bot] avatar ricardogobbosouza 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  avatar  avatar

redirect-module's Issues

How to remove page extension

I am trying to redirection using the following code:

{
    "from": "^/oldPage.php",
    "to": "/newPage",
}

It redirects to /newPage.php, which leads to 404 page, how can I remove the .php from the redirected page?

When new release?

Hi,

I would like to to use onDecode and onDecodeError functions. But it seems latest version in npm is 0.2.0.

Redirect www to non-www with nuxt-redirect module

Hello there,

Please how can I solve this problem with Nuxt-redirect

"Use 301 redirects to drive traffic to URLS with the same domain and sub domain (www and non-www subdomain)."

Move like redirecting www to non-www

Thanks

Does it work with build/generate?

Hi,

First of all, thanks for this great module. It really simplified the task of redirecting routes with Nuxt!

I'm just having a little problem with it: I generated a static page with nuxt generate and deployed it to Netlify. I tried to redirect the base route / to another route /something, but it didn't work. I receive a "page not found" from Netlify. I also tried to make a production SPA with nuxt build but the same happens. In development mode, however, everything works fines. Does the library handles the SPA / static mode or does it rely on Nuxt's universal mode (with a server) to run?

Thanks for your help!

Also affects API calls?

I have the following in nuxt.config.js:

redirect: [
    {
      from: '^(/.+){2,}/$',
      to: (from, req) => {
        return req.url.substr(0, req.url.length - 1)
      }
    },
    {
      from: '/page/1$',
      to: "/"
    }
  ],

This basically insures frontendsite.com/pages/2/ is redirected to frontendsite.com/pages/2, etc...for every page except homepage.

The problem is, this rule seems to be affecting my internal API calls as well, which I make in vuex store. It's stripping apisite.com/api/accounts/auth/login/ to apisite.com/api/accounts/auth/login, which is causing an infinite loop of redirections in the backend.

How can I make sure these rules only apply to "incoming" requests, or only client side requests?

Redirect on client side

Does it really work on the client side too? Judging by the code, serverMiddleware is used. Therefore, when switching pages in SPA mode, it should not work.

Doesn't support sub-domain redirects.

I am currently using now.sh to host my Nuxt application and I do not believe that this package can handle sub-domain redirects.
This is a feature that I could work on. Just let me know.

To add on:

I basically want blah.example.com/abc to get handled by redirect-module and redirect to hello-world.com/abc.

redirect loop

I have the following redirect which seem to cause an infinite redirect loop. I can't quite figure out why.
Do you know why this might be happening? If not, is there a way to set up some kind of log or debugger to track what the redirect module is actually doing behind the scenes for each redirect?

This is the rule:
/get-the-positive-edge => /forms/get-the-positive-edge

And this is what happens when I enter /get-the-positive-edge into the browser:
/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/forms/get-the-positive-edge

Leverage vue-router alias/redirect

Currently, the module only works in universal mode, because a server middleware is used. A possible solution to make the module work in SPA and generate mode would be the alias/redirect options in the vue-router.

Related: #1
Read more

redirect-ssl

I wonder if we could use this module to redirect each url to https, Is there a pattern that someone already used ?

Redirect fails when destination path contains slash

When setting something like this {from: '/from/something', to: '/to/something'}, the server seems to freeze when browsing to /from/something. Not sure what is causing this.

{from: '/from/something', to: '/to'}, works just fine.

Force Trailing Slash - with params

Hi, I am looking for a way to redirect all my urls in order to have them all end in slash. So far I was able to do that, but that method fails when there are params (as in that case the trailing slash should go after the url and before the params).

I opened a thread in StackOverflow, and there is an answer that works in plain regex, but doesn't do the trick with this module (it doesn't redirect at all)

redirect: [
    {
        from: '^[\\w\\.\\/]*(?<!\\/)(\\?.*\\=.*)*$',
        to: (from, req) => {
            const matches = req.url.match(/^.*(\?.*)$/)
            if (matches.length > 1) {
                return matches[0].replace(matches[1], '') + '/' + matches[1]
            }
            return matches[0]
        }
     }
]

You can see the more detailed discussion here
https://stackoverflow.com/questions/56100693/nuxt-js-add-trailing-slash-to-urls-with-params/56211756?noredirect=1#comment99088301_56211756

Recursively Adding Trailing Slash

It appears that the module is recursively adding a trailing slash to the to new URL.

  • Node: 12.8.0
  • Yarn: 1.17.3
  • Nuxt: 2.11.0
  • Redirect Module: 0.3.1

Redirect Rule:

{ from: "/blog/post", to: "/blog/category/post" , statusCode: 301 }

Expected Result:

I expect the URL /blog/post or /blog/post/ (trailing slash) to redirect to /blog/category/post/.

The Problem:

When I visit /blog/post/ the Nuxt site will redirect to /blog/category/post// and the page results in a 404 error and shows my Not Found page.

If I were to visit /blog/post// (notice the double slash), it'll redirect me to /blog/category/post/// and so on. This is a really nice module but this is a big issue considering we cannot control how the user enters the URL. The module works fine if you visit the URL without the trailing slash but that's a specific use case.


To provide some background on this project. I am helping convert my employer's website from a SPA Vue app to an SSR Nuxt app. On the Vue app, we have Nginx rules in place and they work as expected.

If you need more information, please let me know!

Redirects on Firebase

Has anyone got this working with Firebase? Works like a charm running locally but once hosted on Firebase redirects go to my Nuxt 404 page.

Module not working in production after deploying

When I run the project locally in dev or prod mode, everything works. But after I deploy it on a remote server, the module does not work.

The same problem caught up with me when using the @nuxtjs/sitemap module. But you can still survive this.

Force trailing slash

Hi, first of all, thanks a lot for the module.
I'm trying to force a trailing slash in the end of all my urls ( fx: https://domain/this-is-an-url/ ) and I have been trying adapting .htaccess formulas with no luck. So far I've tried:
{ from: '^(.*)[^/]$ ', to: '$1/' } (doesn't work)
{ from: '^(.*)([^/])$ ', to: '/$1$2/' } (works correctly if the url doesn't have a slash, but when it has, it ads a second slash in the end.

Any help would be appreciated!

redirect root

How does one configure it to redirect the root?
i have...
redirect: [ { from: '/', to: '/login' } ]

but it goes in a loop

Middleware shouldn't be async

Middleware created by this module is an async function. That is incorrect because connect framework doesn't await middleware it runs so any exception within the middleware won't be caught and propagated properly.

I don't see a good way to fix it besides dropping support for async to functions.

I've noticed this problem while investigating error that can trigger on res.setHeader with URL with invalid characters (error TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["Location"]).

Get redirects from API without build everytime

/*
 ** Redirect module configuration
 */
redirect: async () => {
    const redirects = await axios.get(process.env.API_BASE_URL + '/application/redirects')
    return redirects.data
},

When my API response to get redirects changes and there are additional redirects. Is it possible update my redirects on nuxt without having to rebuild my app?

Can not redirect request to another script.

What am I doing wrong?

{from: '^/load.js$', to: 'https://code.jquery.com/jquery-3.3.1.min.js', statusCode: 200}

load.js results in a white page while the jquery URL works without issues.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Repository problems

These problems occurred while renovating this repository. View logs.

  • WARN: Using npm packages for Renovate presets is now deprecated. Please migrate to repository-based presets instead.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

circleci
.circleci/config.yml
npm
package.json
  • @babel/core ^7.5.5
  • @babel/preset-env ^7.5.5
  • @commitlint/cli ^8.1.0
  • @commitlint/config-conventional ^8.1.0
  • @nuxtjs/eslint-config ^1.1.2
  • babel-eslint ^10.0.3
  • babel-jest ^24.9.0
  • codecov ^3.5.0
  • consola ^2.10.1
  • eslint ^6.2.2
  • get-port ^5.0.0
  • husky ^3.0.4
  • jest ^24.9.0
  • nuxt-edge ^2.10.0-26112969.c14bb35a
  • request-promise-native ^1.0.7
  • standard-version ^7.0.0

  • Check this box to trigger a request for Renovate to run again on this repository

Support Static generation with Apache or Nginx config generation

Hi,
this is a feature request.

This module is great but doesn't work properly in static mode.

What I suggest is to support only static redirect (w/o logic) and generate an Apache or Nginx config from rules established.
Files generated could be added to the dist folder.

Large Number of Redirects

Hi what is the best way to implement large number of redirects?

My setup works well but my nuxt.config.js is pretty lengthy.

I have 150 product links, does it mean my array in nuxt.config.js is 150 lines long?

Nuxt.config.js

const productRedirects = '[{"from":"/products/all-over-hair-body-shampoo","to":"/all-over-hair-body-shampoo","statusCode":301}]';

module.exports = {
  ...
  ...
  redirects: JSON.parse( productRedirects )
}

How can i redirect to a file

Hey i want to redirect my user when he goes to /cv then redirect him to the last edited pdf in th static folder (+regex filter). Can someone help me ?

unable to map "#"

I wish to use the value in hash to determine my final url

{
        from: "^/handbook#guide$",
        to: (from, req) => {
          return "/myGuidePage";
        }
}

How can i make this work?

when i key in http://localhost/handbook#guide , the redirection doesnt trigger.

can i redirect with path list from api updated daily ?

I used this module to do redirection from 1 path list obtained via api. But it seems that the list is only established once during "build", is there a way for this list to update itself according to the API?
Thank you!

decodeURI causes server error when uri malformed.

While causing an error itself is fine, but there should be some way to catch the error and possibly do a redirect rather then stopping the execution of the app (this mainly applies to malformed links to the app).

Having it throw an exception as it does is fine by default, but there should be some sort of event that can be used to force a redirect. Likely just from a try/catch on the decodeURI function.

Like so (in nuxt.config.js):

redirectError(url, error) {
   return '/?err_info=' + error.code //could pass some info if possible
}

Though I would think it would be better to keep everything under "redirect" but that would likely lead to a breaking change.

Could add info for things like status code and all that in the return, handling even times when the url might be repairable, just not by decodeURI.

This case mainly comes up from migrating to nuxt from a pre-established site where there might be bad url's that need to be handled for a time. In the case here, there are 90k pages in the site migrated and this error has been triggered about once a day since launch, it is also seen in Google Search Console so google reads them as valid links on its end but can't track down the locations of all the links easily. It would be easier to cache the error and redirect that way in my mind.

I plan to eventually do a pull request when I get time, it does not seem like it would be a terribly difficult update to do (and it would get sentry to stop yelling at me lol). Would this be a good way of handling this? Or would there be a better method?

Multi URL to Multi URL Redirects

I am using Nuxt and need to create a multi url to multi url redirect.

An example would be to redirect any urls that contain (anything before)/products/bread(anything after) >>> /shop/product/bread(whatever came after in the url that was redirected). Any help would be greatly appreciated!

Module crashes site

Hi. Every time when I adding module to module section is crashing my site. I got this error
Cannot GET /
Any links from my site return this error. How to fix this? What additional info do you need?

Removing trailing slash with redirects

I'm using your module to remove all trailing slashes from URLs to try and mitigate all the content duplication and to ease the pain that it'd be to do it for Netlify.

Within my nuxt.config.js file I've got the following:

  redirect: [
    {
      // eslint-disable-next-line no-useless-escape
      from: '^.*(?<=\\/)$',
      to: (from, req) => req.url.replace(/\/$/, '')
    }
  ],
  router: {
    trailingSlash: false
  },

I got that code from SO and modified the negative lookbehind to a positive lookbehind. The problem that I've got is that homepage doesn't load by itself, not even when accessed directly, only when clicked from somewhere else, like accessing the about page and then clicking on the logo. Any ideas why?

Also, is it possible to add statusCode: 301?

Thanks.

Conditional redirection issue

Hello!
Need to catch THOUSANDS of old users url's matching: ^/([-_.a-zA-Z0-9]+)$
and redirect them to: /user/$1

This is my rule, where app_pages are the app main paths:

let app_pages = [
	...
	'admin',
	'auth',
	'tests',
	'widgets',
	'dev-login',
	'user',
	...
];
...
...
...
{
	from: '^/([-_.a-zA-Z0-9]+)$',
	to: (from, req) => {
		let param = req.url.match(from)[1];
		
		if (app_pages.includes(param)) {
			//PROBLEM HERE: infinite loop
			return '/$1'
		}
		//this route has an asyncData function that checks $1 to show profile or to return 404
		return '/user/$1'
	},
	statusCode: 301
},
...

How can i do something like return next() or not redirecting if it matches an app_pages path?

Russian characters problem

Hi everyone,
I have problem when redirect from to

{ from: '^/catalog/keyword/(.*)$', to: '/keyword/$1',statusCode: 301 }

Old: /catalog/ΠΎΠ±ΡƒΠ²ΡŒ
New : /keyword/ΠΎΠ±ΡƒΠ²ΡŒ

its not redirecting server error :/

Either borken or I don't know how to use

I'm honestly starting to think something is wrong with my Nuxt.js (2.8.1) setup. No matter how I set up the redirects, nothing is taking effect.

I've tried every single one of these in nuxt.config.js (some are taken from #19 for testing purposes):

{
    from: '^(.*)$',
    to: (from, req) => {
      let trailingUrl = req.url.endsWith('/') ? req.url : req.url + '/'
      return trailingUrl
    }
}
redirect: [
  {
    from: '^/someUrlHere/(.*)$',
    to: (from, req) => {
      const param = req.url.match(/functionAsync\/(.*)$/)[1]
      return `/posts/${param}`
    }
  }
]

I have tried both ways to include in config:

...
router: {
    mode: 'history',
    middleware: ['user-agent']
  },
  redirect: [
    {
      from: '^.*(?<!\/)$',
      to: (from, req) => req.url + '/'
    }
  ],
  build: {
....

or:

modules: [
    '@nuxtjs/pwa',
    ['@nuxtjs/redirect-module', {
      from: '^/about', to: '/'
    }],
    ['@nuxtjs/auth', {

But none works. What am I doing wrong?

Using a pipe in redirect issue

this rule:

{
    from: '^/test|ing/',
    to: '/final',
    statusCode: 301,
  },

redirects to /final%7C/final, should redirect to /final

How can handle base on request

Handle unstored map base on request, more efficient instead store map of redirects.

redirect: async (requestedUri) => {
  // requestedUri could be http://samplesite.tld/old-article/128904731/
  const newUrl = await axios.get("/newArticleId?id=" + requestedUri) // It'll wait!

  // for example newUrl could be `http://samplesite.tld/article/5e18dec80000000000000000/`
  // or not found could return false
  if (newUrl) { // found
     return newUrl; // new url 
  }
  // not found
  return false; // continue default 404
}

Could we use this method ? How?
If yes please update documentation to how to do this ?

Cache response

Is there a way to Cache the 301 redirects if they are coming from a server so it doesn't have to be fetched for every user on every pageload?

Say it is being cached for 24 hours or one day or so...

0.2.0 forces nuxt fatal error

After updating to 0.2.0 i get this error when running npm run dev | build | start:

export default async function nuxtRedirect(moduleOptions) {
^^^^^^

SyntaxError: Unexpected token export
    at Object.Module._extensions..js (module.js:646:10)
    at Object.Module._extensions..js (module.js:646:10) ]


βœ– Nuxt Fatal Error  
 SyntaxError: Unexpected token export

Node Version: 8.10.0

Solution 2:*
use Node 10.x.x

A hint in the Docs would be nice :)

Issue with redirect handling

I'm trying to make redirect 2 distincts URLs into one.
/test and /test2 into notatest.

I tried
{ from: '^/test', to: '/notatest', statusCode: 301 }, { from: '^/test2', to: '/notatest', statusCode: 301 },

And
{ from: '^/test(.*)', to: '/notatest', statusCode: 301 },

With the same result: /test redirects to notatest and /test2 redirects to /notatest2 instead of /notatest.

Usage with the path-to-regexp lib

Vue router uses path-to-regexp.

Example proposal for this package:

  {
    from: '/library/:category/:book', to: '/new-library/:book'
  }

It’s convenient when you can use this kind of parameters in URLs.

Plus sign (+) origin URL give 404 in Nuxt

When trying to redirect from:

"^/original+url+to+redirect"

Appears 404 before redirecting.
Also tried with %2B and %20 and same not found error.
I'm missing something?

Accept function for the to parameter

Currently, the to parameter of a redirect rule can only be a string (optionally with regex groups). To give the developers even more freedom, why not accepting a function that will be executed and returns the correct to route based on the from route.

Example:

{ from: '^/test/a*$', to: fromRoute => fromRoute.includes('aha') ? '/aha' : '/noo' }

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.