Friday, February 25, 2022

sample nginx configuration with locations,variables,conditionals,redirects,rewrites

 /sites/demo/

index.html

style.css

thum.png


/etc/nginx/nginx.conf

--------

events{}

http{

 types{

   text/html html;

   text/css css; 

 }

 server{

 listen 80;

 server_name ip_local_machine/*.mydomain.com;

 

 root /sites/demo;

}

}


systemctl reload nginx

nginx -t --> to check syntax

curl -I http://ip/style.css



//or import the mime.types file  instead of types.

include mime.types;


---------------------

location block


server {

 //prefix, anything starting with /greet, /greet/more

 location /greet {

   return 200 'Hello from NGINX "/greet" location'

 }

}


exact match:

location = /greet {}


regular expression:

location ~ /greet[0-9] {}

~* for case-insensitive


regular expression wins over prefix match in any order written.


^~ (preferential prefix match)same as prefix but preference wins over regular expression



variables:

---

configuration variables:

set $var 'something';


NGINX Module Variables

$http, $uri, $args


server {

 //prefix, anything starting with /greet, /greet/more

 location /greet {

   return 200 "$host\n$uri\n$args"

 }

}


http://url?name=ray

collected in $arg_name


conditionals:

------

server{

if ( $arg_apikey != 1234 ){

  return 401 "Incorrect API key"

}

location{}

}


server{

set $weekend 'No';

if ( $date_local ~ 'Saturday' ){

  Set $weekend 'Yes';

}

location /is_weekend{

  return 200 $weekend;

}

}


---------

redirect:

--

server{

listen 80;

server_name 167.99.93.26;

root /sites/demo;

location /logo{

  return 307 /thumb.png;

}

}


rewrite:

---

url won't changes, internally it targets to the location.


server{

listen 80;

server_name 167.99.93.26;

root /sites/demo;

//rewrite ^/user/\w+ /greet; //but all the evaluation dones again for rewritten target

rewrite ^/user/(\w+) /greet/$1; //capture groups

rewrite ^/greet/jony /thumb.png;

location /greet{

  return 200 'hello user';

}


location /greet/john{

  return 200 'hello john';

}

}


adding: rewrite ^/user/\w+ /greet last; //will make it as last time to rewritten

No comments:

Post a Comment