refactor the redirect middleware