Making nginx check parameter in url

72,366

Solution 1

You better use http://example.com/?mobile=1 (argument with value). In this case checking is simple:

if ($arg_mobile) {
    return 302 http://m.example.com/;
}

Checking for argument existance is usually done with regexp like if ($args ~ mobile) but it's error-prone, because it will match mobile anywhere, e.g. http://example.com/?tag=automobile.

Solution 2

If you know you have only 1 parameter {{variable}} to switch, you can detect if exist like this

if ($request_uri ~ '\?{{variable}}') {
    ...
}

for example

if ($request_uri ~ '\?mobile') {
    return 302 https://m.example.com;
}

Also I suggest consider use this redirection

http://{{domain}}.{{tld}}/mobile -> http://m.{{domain}}.{{tld}}

location ~ '/mobile'
    return 301 'https://m.{{domain}}.{{tld}}';
}

for example

location ~ '/mobile'
    return 301 'https://m.example.com';
}
Share:
72,366

Related videos on Youtube

user2650277
Author by

user2650277

Updated on April 22, 2020

Comments

  • user2650277
    user2650277 about 4 years

    I want to check if a parameter is present in a url in nginx and then rewrite.How can i do that?

    For e.g if url is http://website.com/?mobile then redirect user to http://m.website.com

    • Alexey Ten
      Alexey Ten about 10 years
      Try to use some value if you could. Checking that parameter has some value is simple if ($arg_mobile). Checking if there is empty argument mobile is not so clear and error-prone.
    • user2650277
      user2650277 about 10 years
      @AlexeyTen could you post it as an answer with an example...i never worked with arguments before
  • user2650277
    user2650277 about 10 years
    All i need to do is add the code above to my nginx conf.Does nginx already know that $arg_mobile will check for ?mobile-1.
  • Alexey Ten
    Alexey Ten about 10 years
    (=) — equality sign, not (-) hyphen. It will check for mobile=pretty-anything except 0 (zero) and empty argument.
  • raksja
    raksja over 6 years
    i'm getting nginx: [emerg] unknown directive "if($arg_querystringkey)" for version nginx/1.12.2. Is this not supported any more?
  • Alexey Ten
    Alexey Ten over 6 years
    @raksja try to add space after “if”
  • raksja
    raksja over 6 years
    thanks @AlexeyTen, it worked. I have a followup question on dynamic proxy_pass variable in here, can you pls take a look nginx dynamic proxy pass variable
  • Zafar
    Zafar about 3 years
    thanks, way defined to get the arguments value helped me i.e. $arg_mobile