Skip to content

Instantly share code, notes, and snippets.

@jovertical
Last active December 28, 2019 09:47
Show Gist options
  • Select an option

  • Save jovertical/fd46a591555bbf262b9ce806a26991f4 to your computer and use it in GitHub Desktop.

Select an option

Save jovertical/fd46a591555bbf262b9ce806a26991f4 to your computer and use it in GitHub Desktop.
Nginx Configration
Nginx Configuration
  1. Exact Match =
location = /greeting {
  return 200 'Hello There! Matched using "Exact Pattern"';
}
  1. Preferential Prefix Match ^~
location ^~ /greeting {
  return 200 'Hello There! Matched using "Preferential Prefix Pattern"';
}
  1. REGEX Match ~
location ~ /greet[ing] {
  return 200 'Hello There! Matched using "REGEX Pattern"';
}
  1. Prefix Match
location /greeting {
  return 200 'Hello There! Matched using "Prefix Pattern"';
}
server {
  ...
  set $weekend 'No';

  if ( $date_local ~ 'Saturday|Sunday' ) {
    set $weekend 'Yes';
  }

  location /shoud-rest {
    return 200 "Need to rest? $weekend \nWhy? Because it's $date_local";
  }
  ...
}

Redirect Example

When address: /logo was visited, redirect to /img.jpg

location = /logo {
  return 307 /img.jpg;
}

Rewrite Example

Give "Hello John" if /user/john is visited, otherwise give "Hello User", all of this without redirecting from /user/*.

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

location /greet {
  return 200 "Hello User";
}

location /greet/john {
  return 200 "Hello John";
}

Try Files Example

Assuming that /img.jpg exists on root, that image would be loaded first, if not, the /greet path would be. Nginx' try_files works similar to rewrite.

try_files $uri /img.jpg /greet /custom_404;

location /greet {
  return 200 "Hello User";
}

Custom 404

Using try_files, for instance when /does-not-exists is visited, it will then point to @custom_404 in which you can handle the error yourself.

try_files $uri /greet @custom_404;

location @custom_404 {
  return 404 "Sorry, we cannot find the page you are looking for";
}

By default, there are 2 log types in Nginx: Access Log and Error Log

Custom Access Log

When path: /friends is visited, it will log to the file /var/log/nginx/friends.access.log instead of the default /var/log/nginx/access.log

location /friends {
  access_log /var/log/nginx/friends.access.log;
  return 200 "Your friends are waiting for you";
}

Disable Access Log

To disable logging in a given context, for example in path: /enemies

location /enemies {
  access_log off;
  return 200 "Your enemies are also your friends";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment