2

I am trying to achieve a redirection in nginx that should happen only if a specific argument and value pair is existing.

For example : https://www.mywebsite.com/search?abc=453?hjh=7484?foo=bar?joe=blah

should be proxied to an application only if hjh=7484 is present in the request_uri. This can be anywhere in the whole URL, that said its position is not fixed.

If the incoming request against search page doesn't have hjh=7484 the request should be redirected to https://www.mynewwebsite.com/

I have tried putting

    location ~* /search(.*)?hjh=7484(.*)?$ {
    proxy_pass $my_app;
}

Above is ending in 404.

2019/01/21 15:48:47 [error] 113#113: *109 open() "/usr/share/nginx/html/search" failed (2: No such file or directory),

If I change the above regex and allow any requests to search page to be passed its working!

2
  • The location and rewrite directives test a normalized URI which does not include the query string. You need to look at the $request_uri or $args variable with an if or map statement. See this answer for an example. – Richard Smith Jan 21 '19 at 16:13
  • I think this is also answered here: serverfault.com/questions/811912/… – Jaime D Jan 21 '19 at 16:38
1

The location only matches the URI path component. It does not match query strings.

You can check the value of the argument instead, for instance:

location /search {
    if ($arg_hjh = 7484) {
        proxy_pass @my_app;
    }
    # do something else
}
4
  • Yes I had tried the same and was still ending up in a 404! The config I tried was like ` location /search { if ($arg_hjh=7484) { proxy_pass $my_app; } } – Raju Divakaran Jan 21 '19 at 16:42
  • Have you checked where the 404 is sent from? It is possible that nginx proxies the request forward, but your app cannot find the resource. – Tero Kilkanen Jan 21 '19 at 19:09
  • @RajuDivakaran What is in the nginx error log? – Michael Hampton Jan 21 '19 at 19:40
  • I was just getting 404, with error saying 2019/01/21 15:48:47 [error] 113#113: *109 open() "/usr/share/nginx/html/search" failed (2: No such file or directory), – Raju Divakaran Jan 22 '19 at 9:43
0

I am able to get this working by using the method posted here Can nginx location blocks match a URL query string?

error_page 419 = @searchquery;

if ($args ~ "(^|&)hjh=7484" ) {
    return 419;
}

location @searchquery {
    proxy_pass $my_app;
}

Now the problem is any request with that argument, not only to search page will be processed. What would be the best way to make this restricted only to /search location ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.