Fix redirect bug and refactor