Skip to content
Free Indian Tools

SEO

nginx redirect cheatsheet — return 301 patterns you actually need

nginx redirect snippets for the patterns you actually need — apex to www, http to https, single page moves, section moves, regex patterns. Copy and ship.

11 April 2026 · 2 min read


Quick frame: The nginx redirect patterns you actually need: apex to www, http to https, single-page move, section move, regex pattern, and trailing slash normalisation. All using return 301 for performance.

Pattern 1: apex to www

server {
  listen 443 ssl;
  server_name example.in;
  return 301 https://www.example.in$request_uri;
}

Combine with the matching SSL cert covering both apex and www subdomain. Most Indian SMBs serve www as canonical.

Pattern 2: http to https

server {
  listen 80;
  server_name www.example.in;
  return 301 https://$host$request_uri;
}

Always pair with HSTS header for follow-up protection.

Pattern 3: single page move

location = /old-page {
  return 301 /new-page;
}

Use location = for exact match (faster than regex).

Pattern 4: full section move

location ^~ /old-blog/ {
  rewrite ^/old-blog/(.*)$ /blog/$1 permanent;
}

^~ prefix match + rewrite ... permanent for the 301.

Pattern 5: regex pattern

location ~* ^/products/(\d+)/old-style$ {
  return 301 /products/$1;
}

~* for case-insensitive regex. $1 captures the digit group.

Pattern 6: trailing slash normalisation

Add trailing slash if missing (skip files with extensions):

rewrite ^([^.]*[^/])$ $1/ permanent;

Strip trailing slash:

rewrite ^/(.*)/$ /$1 permanent;

Performance: return vs rewrite

return is faster — it short-circuits nginx without the rewrite module. Use rewrite only when you need regex capture groups for the destination. For plain URL-to-URL redirects, return wins.

After editing

nginx -t           # validate config
nginx -s reload    # graceful reload (existing connections finish on old config)

Use the nginx redirect generator to build blocks from a URL list, then test flatness with the redirect chain visualiser.

For Apache equivalents, see Apache .htaccess redirect cheatsheet.

FAQ

Q. Why is my redirect getting cached even after a config change? A. 301s are aggressively browser-cached. Clear browser cache or test in incognito. To force re-evaluation, push as 302 first, then back to 301 after observation.

Q. Should I redirect at server level or in PHP / app code? A. Always server level for SEO redirects — faster, more reliable, no app overhead.

Q. How do I redirect to a different domain? A. Use the full URL: return 301 https://www.newdomain.in$request_uri;

Try the free tool

nginx Redirect Generator

Generate nginx `return 301` blocks for single URL or pattern redirects.

Open nginx Redirect Generator

Related guides