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
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.
$arg_mobile will check for ?mobile-1.mobile=pretty-anything except 0 (zero) and empty argument.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';
}
if ($arg_mobile). Checking if there is empty argumentmobileis not so clear and error-prone.