Skip to content

Instantly share code, notes, and snippets.

@jrom
Created February 7, 2012 17:14
Show Gist options
  • Select an option

  • Save jrom/1760790 to your computer and use it in GitHub Desktop.

Select an option

Save jrom/1760790 to your computer and use it in GitHub Desktop.
nginx hack for multiple conditions
if ($request_uri = /) {
set $test A;
}
if ($host ~* teambox.com) {
set $test "${test}B";
}
if ($http_cookie !~* "auth_token") {
set $test "${test}C";
}
if ($test = ABC) {
proxy_pass http://teambox-cms.heroku.com;
break;
}
@nkn786

nkn786 commented Nov 30, 2017

Copy link
Copy Markdown

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;
break;
}
proxy_pass http://127.0.0.1:1234;

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.

Regards,
Naveen

@NickHibma

Copy link
Copy Markdown

nkn786, try $http_x_token.

@havilchis

Copy link
Copy Markdown

You truly are the king of kings

@onier

onier commented Aug 10, 2018

Copy link
Copy Markdown

awesome ! 666666

@ezra-obiwale

Copy link
Copy Markdown

Nice. Thanks

@escudero89

Copy link
Copy Markdown

Awesome man, thanks.

@Azzurite

Azzurite commented Sep 6, 2019

Copy link
Copy Markdown

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;
    "/:teambox.com:auth_token"  1;
}

server {
    if ( $test ) {
      proxy_pass http://teambox-cms.heroku.com;
      break;
    }
}

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

@boddumanohar

Copy link
Copy Markdown

this is awesome!

@GoodJob

GoodJob commented Mar 17, 2021

Copy link
Copy Markdown

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

How to write this condition?

if ($host *.teambox.com) {
set $subdomain_name = ?;
}

Thanks!

@lordspace

lordspace commented Jun 26, 2023

Copy link
Copy Markdown

Awesome!!!! Thanks!
If somebody needs an explanation what the code does is it sequentially appends different letters to one variable.
When all the letters are present that means that all the required conditions have been met.

@eladnava

Copy link
Copy Markdown

This works great!

I recommend initializing the $test variable outside and above all the conditional statements to avoid endless using uninitialized "test" variable errors piling up in /var/log/nginx/error.log as follows:

set $test "";

@samezarus

Copy link
Copy Markdown

👍👍👍 Дядя, спасибо тебе !!!

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