0
0
Nginxdevops~5 mins

Conditional redirects with if in Nginx - Commands & Configuration

Choose your learning style9 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.