HACKER Q&A
📣 always_imposter

Help with Nginx Internal Redirect Based on Subdomain Validation


I'm trying to set up an NGINX server block to handle requests based on subdomain validation. Here’s what I’m aiming for:

Incoming Request: A request comes in with a subdomain (e.g., jiffy.example.com). Validation: The subdomain gets validated by my backend API which is an upstream server(http://backend_api/api/user/validate/$subdomain). The API responds: 200 OK if the subdomain is valid. 404 Not Found if the subdomain is invalid. Internal Redirects: Based on the API response, NGINX should: Route valid subdomains to a @userPage location (proxying to a userPage service). Route invalid subdomains to a @not_found location (proxying to a custom "not found" page).

Here's what I have so far:

``` server { listen 443 ssl; server_name ~^(?.+)\.${USERPAGE_SERVER_NAME}$;

    ssl_certificate ${SSL_CERT_PATH};
    ssl_certificate_key ${SSL_KEY_PATH};

    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    ssl_ciphers HIGH:!aNULL:!MD5;

    # Validate the subdomain
    location / {
        
        set $validation_url http://backend_api/api/user/validate/$subdomain;

        proxy_cache valid_subdomains;
        proxy_cache_key "$subdomain";
        proxy_pass_request_headers off;
        proxy_set_header Host $host;
        proxy_pass $validation_url;

    }    

    # Handle valid subdomain redirect
    location @userPage {
        proxy_pass https://${DEVELOPMENT_USERPAGE_URL};
    }

    # Handle invalid subdomain redirect
    location @not_found {
        proxy_pass https://${DEVELOPMENT_NOT_FOUND_URL};
    }
  }
```

What am i doing wrong here? I read about X-Accel-Redirect flag but I am not able to understand how to capture that flag in the response header if I send it as a response header from my api?

Any help would be appreciated.


  👤 rudasn Accepted Answer ✓
Nginx auth module may help you with these kind of requests.