webpage
redirect

How do I redirect to another webpage?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Redirecting users to another webpage can be done at server, proxy, or browser level, and each choice has different behavior for users and search engines. Many redirect problems come from using the right URL with the wrong status code. The best approach is to pick redirect type by intent, then verify headers and chain behavior in production.

Server-Side Redirects First

For canonical URL changes, domain migration, and SEO-sensitive routing, server-side redirects should be default. They return explicit HTTP status and Location header, which browsers and crawlers understand.

Common status meanings:

  • 301 permanent move.
  • 302 temporary move.
  • 303 after a POST when next request should be GET.
  • 307 temporary redirect preserving method.
  • 308 permanent redirect preserving method.

Express example:

javascript
1import express from "express";
2
3const app = express();
4
5app.get("/old-page", (req, res) => {
6  res.redirect(301, "/new-page");
7});
8
9app.post("/submit", (req, res) => {
10  // Post-Redirect-Get pattern
11  res.redirect(303, "/thank-you");
12});
13
14app.listen(3000);

Picking correct code avoids cache and method issues.

Proxy-Level Redirects for Infrastructure Rules

If redirect is purely URL or domain policy, put it in reverse proxy to keep behavior centralized and fast.

NGINX example:

nginx
1server {
2    listen 80;
3    server_name example.com;
4    return 301 https://www.example.com$request_uri;
5}
6
7server {
8    listen 443 ssl;
9    server_name www.example.com;
10
11    location = /legacy {
12        return 301 /new-home;
13    }
14}

This works well for HTTP to HTTPS enforcement and old-path migration.

Keep ownership clear. If both proxy and app redirect the same route, loops are easy to create.

Client-Side Redirects and SPA Routing

Browser redirects are useful for UI decisions after state checks, but they are weaker for canonical migration.

Basic JavaScript options:

html
1<script>
2  // adds history entry
3  window.location.href = "/dashboard";
4
5  // replaces current entry
6  // window.location.replace("/dashboard");
7</script>

In single-page apps, use router APIs instead of full reload when possible.

javascript
1import { useNavigate } from "react-router-dom";
2
3function LoginComplete() {
4  const navigate = useNavigate();
5
6  const go = () => {
7    navigate("/dashboard", { replace: true });
8  };
9
10  return <button onClick={go}>Continue</button>;
11}

Router navigation keeps app state and avoids extra network round trips.

Redirect After Form Submission

A frequent bug is handling form POST and directly rendering success page at same URL. This can cause duplicate submissions on refresh.

Use Post-Redirect-Get:

  1. Accept POST.
  2. Store result.
  3. Return 303 redirect to confirmation page.
  4. Browser requests confirmation with GET.

This pattern improves UX and reduces duplicate writes.

Validate Redirect Behavior

After deployment, validate with CLI and browser tools.

bash
curl -I https://example.com/old-page
curl -I -L https://example.com/old-page

Check:

  • expected status code
  • correct Location header
  • chain length
  • final destination URL

Aim for one-hop redirects. Long chains increase latency and reduce crawl efficiency.

SEO and Caching Notes

For permanent moves, update canonical tags and internal links to target URL directly. Redirect should be a transition path, not permanent internal dependency. CDN caches can store redirect responses aggressively, so include cache invalidation in rollout plans when rules change.

Also keep analytics tagging in mind. Redirecting through intermediate paths can fragment attribution if tracking parameters are not preserved.

Security Considerations

Validate redirect targets if URL is influenced by user input. Open redirect vulnerabilities can enable phishing and token leakage.

Safe pattern:

  • allow-list internal targets
  • reject unknown hosts
  • normalize and validate path

Never redirect directly to unvalidated query parameter values.

Common Pitfalls

A common pitfall is using JavaScript redirect for a permanent URL migration that should be server-side. Another is returning 302 by habit for long-term changes, which weakens caching and SEO clarity. Teams also create loops when proxy and app rules overlap. Form workflows often misuse 302 where 303 is correct after POST. Finally, missing validation on user-provided redirect targets introduces open redirect risk. Redirects are simple to issue and surprisingly easy to get subtly wrong.

Summary

  • Prefer server-side redirects for canonical URL management.
  • Choose status codes by behavior, not convenience.
  • Use proxy redirects for infrastructure-level URL rules.
  • Use client-side redirect only for UI-driven navigation logic.
  • Validate redirect headers, chain length, and final destination.
  • Protect against open redirects by validating target URLs.

Course illustration
Course illustration

All Rights Reserved.