Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
nginx hack for multiple conditions
if ($request_uri = /) {
set $test A;
if ($host ~* {
set $test "${test}B";
if ($http_cookie !~* "auth_token") {
set $test "${test}C";
if ($test = ABC) {
Copy link

GeoffreyHervet commented Dec 1, 2016

Thanks !

Copy link

sinasalek commented Jan 3, 2017

You are a god :D

Copy link

PeterRJones commented Feb 17, 2017

Great solution! For those suggestion a map, that is great if condition variable remains the same for all checks. If not, this solution trumps map.

Copy link

danlsgiga commented Apr 5, 2017

Thanks for this but I prefer to use @songsfromthewood map solution.

Copy link

glamrock commented May 16, 2017

@songsfromthewood's example works great, with the exception of empty strings (like referer or useragent). But for blank referer and useragent, it's still pretty good :D

Copy link

aluttik commented Aug 30, 2017

for those who haven't read this yet: If Is Evil

Copy link

nkn786 commented Nov 30, 2017

Hi All,

I am checking the header "x-token" present from the incoming request if not i have to send 403 in nginx below is my code

if ($http_x-token = ""){
return 403;

But here "-" is the problem so how do i achieve this. if i pass the header as "xtoken" its working as expected
Could you please any one guide on this query.


Copy link

NickHibma commented Dec 15, 2017

nkn786, try $http_x_token.

Copy link

havilchis commented Jul 28, 2018

You truly are the king of kings

Copy link

onier commented Aug 10, 2018

awesome ! 666666

Copy link

ezra-obiwale commented Aug 17, 2018

Nice. Thanks

Copy link

escudero89 commented Jun 11, 2019

Awesome man, thanks.

Copy link

Azzurite commented Sep 6, 2019

Seems, you are not familiar with map, or do not like it. More short and elegant:

":" is used just like delimiter, you can use any other symbol not used in checked variables.

map "$request_uri:$host:$http_cookie" $test {
    default 0;
    "/"  1;

server {
    if ( $test ) {

@songsfromthewood Actually no, yours does not match "" while the original post does.

Copy link

boddumanohar commented Mar 13, 2020

this is awesome!

Copy link

GoodJob commented Mar 17, 2021

Need explanation.... what actually this does:
if ($host ~* {
set $test "${test}";
Does it takes "this" or what? Thanks!

How to write this condition?

if ($host * {
set $subdomain_name = ?;


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment