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';
}
Related videos on Youtube
Author by
user2650277
Updated on April 22, 2020Comments
-
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 tohttp://m.website.com
-
Alexey Ten about 10 yearsTry to use some value if you could. Checking that parameter has some value is simple
if ($arg_mobile)
. Checking if there is empty argumentmobile
is not so clear and error-prone. -
user2650277 about 10 years@AlexeyTen could you post it as an answer with an example...i never worked with arguments before
-
-
user2650277 about 10 yearsAll 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 about 10 years(=) — equality sign, not (-) hyphen. It will check for
mobile=pretty-anything
except0
(zero) and empty argument. -
raksja over 6 yearsi'm getting nginx: [emerg] unknown directive "if($arg_querystringkey)" for version nginx/1.12.2. Is this not supported any more?
-
Alexey Ten over 6 years@raksja try to add space after “if”
-
raksja over 6 yearsthanks @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 about 3 yearsthanks, way defined to get the arguments value helped me i.e. $arg_mobile