37

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

2
  • 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. Commented Jun 2, 2014 at 6:52
  • @AlexeyTen could you post it as an answer with an example...i never worked with arguments before Commented Jun 2, 2014 at 6:54

3 Answers 3

68

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.

Sign up to request clarification or add additional context in comments.

7 Comments

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.
(=) — equality sign, not (-) hyphen. It will check for mobile=pretty-anything except 0 (zero) and empty argument.
i'm getting nginx: [emerg] unknown directive "if($arg_querystringkey)" for version nginx/1.12.2. Is this not supported any more?
@raksja try to add space after “if”
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
|
3

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';
}

Comments

0

You can try this to match your param

if ($args ~ '\bmobile[=&]?' )
{
    return 302 http://m.example.com/;
}

as this will match 'mobile' anywhere in $args, with or without value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.