Skip to content

How to Use Nginx return for Redirects

DodaTech Updated 2026-06-24 2 min read

The return directive provides simple, efficient redirects. It is preferred over rewrite for most redirect scenarios. This guide walks through the specific troubleshooting steps to diagnose and resolve redirect issues.

Before You Begin

Before you begin, be sure to have the following in place:

  • A Linux server with the relevant software installed
  • Access to the command line interface
  • Appropriate permissions (root or sudo)

Quick Fix

Wrong

rewrite ^/old$ /new permanent; (using rewrite for simple redirect)

Wrong: Using rewrite for simple redirects

location /old {\n    return 301 /new;\n}

Right: Using return for simple redirects (faster)

Output

Redirect configured:\n  /old → /new (301 permanent)\n  Status code: 301 Moved Permanently

Prevention

To avoid future issues, follow these best practices:

  • Use return instead of rewrite for simple path-to-path redirects
  • Use 301 for permanent moves, 302 for temporary redirects
  • Use return 404 to return a 404 without redirecting
  • Use return with variables: return 301 https://$host$request_uri;
  • Place return in location blocks for path-specific redirects

DodaTech Tools

For further assistance with any of the above issues, consider using DodaTech consulting services or DodaTech tutorials for more in-depth guidance.

Common Mistakes with return redirect

  1. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  2. Using return to exit a function early instead of wrapping a pure value in the monad
  3. Mixing let bindings with <- bindings in do notation, producing type errors

These mistakes appear frequently in real-world NGINX code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

What HTTP status codes can I use with return?|||200, 204, 301, 302, 303, 307, 308, 400, 401, 402, 403, 404, 405, 406, 408, 410, 411, 413, 414, 415, 416, 417, 426, 429, 444, 451, 494, 495, 496, 497, 500, 501, 502, 503, 504.
When should I use 301 vs 302? 301 (Moved Permanently) tells browsers and search engines the redirect is permanent. 302 (Found) is for temporary redirects.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro