Bird
Raised Fist0
Nginxdevops~5 mins

Conditional redirects with if in Nginx - Commands & Configuration

Choose your learning style10 modes available
Introduction
Sometimes you want to send visitors to different web pages based on conditions like the URL they requested. Nginx lets you do this using conditional redirects with the if directive. This helps control traffic flow on your website easily.
When you want to redirect users from an old page URL to a new one only if they visit the old URL.
When you want to send mobile users to a mobile version of your site based on their user agent.
When you want to block access to certain URLs and redirect those requests to a warning page.
When you want to redirect users to HTTPS only if they visit the site using HTTP.
When you want to redirect requests with specific query parameters to a special page.
Config File - nginx.conf
nginx.conf
server {
    listen 80;
    server_name example.com;

    location / {
        if ($request_uri = "/old-page") {
            return 301 https://example.com/new-page;
        }
        if ($http_user_agent ~* "Mobile") {
            return 302 https://m.example.com$request_uri;
        }

        # Default behavior
        try_files $uri $uri/ =404;
    }
}

This configuration listens on port 80 for example.com.

Inside the main location, it checks if the requested URL is exactly "/old-page" and redirects permanently (301) to "/new-page".

It also checks if the user agent contains "Mobile" (case insensitive) and redirects temporarily (302) to the mobile site with the same path.

If none of these conditions match, it tries to serve the requested file or returns a 404 error.

Commands
Check the nginx configuration file for syntax errors before applying changes.
Terminal
sudo nginx -t
Expected OutputExpected
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful
Reload nginx to apply the new configuration without stopping the server.
Terminal
sudo systemctl reload nginx
Expected OutputExpected
No output (command runs silently)
Test the redirect for the old page URL to verify it sends a 301 redirect to the new page.
Terminal
curl -I http://example.com/old-page
Expected OutputExpected
HTTP/1.1 301 Moved Permanently Server: nginx Location: https://example.com/new-page Content-Type: text/html Content-Length: 178 Connection: keep-alive
Test the redirect for mobile user agents to verify it sends a 302 redirect to the mobile site.
Terminal
curl -I -A "Mozilla/5.0 (iPhone) Mobile" http://example.com/somepage
Expected OutputExpected
HTTP/1.1 302 Found Server: nginx Location: https://m.example.com/somepage Content-Type: text/html Content-Length: 178 Connection: keep-alive
Key Concept

If you remember nothing else from this pattern, remember: nginx's if directive lets you check conditions and redirect users based on request details.

Common Mistakes
Using if inside location blocks for complex logic that changes request processing.
Nginx's if directive can cause unexpected behavior if used improperly, especially for rewriting or proxying.
Use if only for simple checks and redirects; for complex logic, use map or separate location blocks.
Forgetting to test nginx configuration with 'nginx -t' before reloading.
Syntax errors can cause nginx to fail to reload, leading to downtime.
Always run 'sudo nginx -t' to verify configuration before reloading.
Using 302 redirect when a permanent redirect (301) is intended.
Browsers may cache 301 redirects, so using 302 by mistake can cause confusion.
Use 'return 301' for permanent redirects and 'return 302' for temporary ones.
Summary
Use the if directive inside location blocks to check request conditions like URL or user agent.
Use 'return' with status codes 301 or 302 to perform redirects based on those conditions.
Always test your nginx configuration with 'nginx -t' before reloading to avoid errors.

Practice

(1/5)
1. What does the if directive do in an nginx configuration for conditional redirects?
easy
A. It logs all user requests to a file.
B. It checks a condition and performs an action like redirect if true.
C. It restarts nginx automatically.
D. It permanently disables the server.

Solution

  1. Step 1: Understand the role of if in nginx

    The if directive evaluates a condition inside the server or location block.
  2. Step 2: Recognize its use for redirects

    If the condition is true, nginx can perform actions like return to redirect users.
  3. Final Answer:

    It checks a condition and performs an action like redirect if true. -> Option B
  4. Quick Check:

    if checks condition for redirect [OK]
Hint: Remember: if tests, return redirects [OK]
Common Mistakes:
  • Thinking if restarts nginx
  • Confusing if with logging
  • Assuming if disables server
2. Which of the following is the correct syntax to redirect all requests from /old to /new using if in nginx?
easy
A. if ($request_uri == "/old") return 301 /new;
B. if $request_uri == "/old" { return 301 /new; }
C. if ($request_uri = "/old") { return 301 /new; }
D. if $request_uri = "/old" return 301 /new;

Solution

  1. Step 1: Check correct if syntax in nginx

    nginx requires parentheses around the condition and uses a single equals sign for string comparison.
  2. Step 2: Confirm the block and return statement

    The condition must be inside parentheses, followed by braces with the return directive inside.
  3. Final Answer:

    if ($request_uri = "/old") { return 301 /new; } -> Option C
  4. Quick Check:

    Parentheses and braces with single = [OK]
Hint: Use parentheses and single = inside if [OK]
Common Mistakes:
  • Using double == instead of single =
  • Omitting parentheses around condition
  • Missing braces around return
3. Given this nginx snippet:
server {
  listen 80;
  server_name example.com;
  location / {
    if ($http_user_agent ~* "Mobile") {
      return 302 /mobile;
    }
  }
}

What happens when a user with user agent "Mozilla Mobile" visits http://example.com/?
medium
A. They are redirected to /mobile with a 302 status.
B. They see the normal homepage without redirect.
C. They get a 404 error.
D. The server crashes due to syntax error.

Solution

  1. Step 1: Understand the if condition with regex

    The condition checks if the user agent contains "Mobile" ignoring case.
  2. Step 2: Apply the redirect action

    Since "Mozilla Mobile" matches, nginx returns a 302 redirect to /mobile.
  3. Final Answer:

    They are redirected to /mobile with a 302 status. -> Option A
  4. Quick Check:

    User agent matches regex, triggers redirect [OK]
Hint: Regex ~* means case-insensitive match [OK]
Common Mistakes:
  • Ignoring case sensitivity in regex
  • Assuming no redirect happens
  • Thinking syntax error occurs
4. Identify the error in this nginx config snippet for redirecting /old to /new:
if $request_uri = "/old" {
  return 301 /new;
}
medium
A. Missing parentheses around the condition in if.
B. Using double equals instead of single equals.
C. Missing semicolon after if statement.
D. Incorrect return status code.

Solution

  1. Step 1: Check if syntax requirements

    nginx requires the condition inside parentheses after if.
  2. Step 2: Verify the given snippet

    The snippet lacks parentheses around $request_uri = "/old", causing syntax error.
  3. Final Answer:

    Missing parentheses around the condition in if. -> Option A
  4. Quick Check:

    if needs parentheses [OK]
Hint: Always wrap if conditions in parentheses [OK]
Common Mistakes:
  • Forgetting parentheses in if
  • Confusing single and double equals
  • Thinking semicolon needed after if
5. You want to redirect users accessing /old only if they come from the domain example.com. Which nginx config snippet correctly does this using if?
hard
A. if ($request_uri = "/old" && $http_referer ~* "example.com") { return 301 /new; }
B. if ($request_uri = "/old") { return 301 /new if ($http_referer ~* "example.com"); }
C. if ($request_uri = "/old" || $http_referer ~* "example.com") { return 301 /new; }
D. if ($request_uri = "/old") { if ($http_referer ~* "example.com") { return 301 /new; } }

Solution

  1. Step 1: Understand nginx if limitations

    nginx does not support combining conditions with && inside a single if.
  2. Step 2: Use nested if for multiple conditions

    Nested if blocks allow checking one condition inside another.
  3. Step 3: Analyze options

    if ($request_uri = "/old") { if ($http_referer ~* "example.com") { return 301 /new; } } uses nested if correctly; others use unsupported syntax or wrong logic.
  4. Final Answer:

    if ($request_uri = "/old") { if ($http_referer ~* "example.com") { return 301 /new; } } -> Option D
  5. Quick Check:

    Nested if for multiple conditions [OK]
Hint: Use nested if for multiple conditions in nginx [OK]
Common Mistakes:
  • Trying to use && inside one if
  • Using || instead of && for AND logic
  • Placing return incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard