Link Search Menu Expand Document

=== Resources

=== Topics

— GZIP

src: https://docs.nginx.com/nginx/admin-guide/web-server/compression/

  • can be included in the http context or in a server or location configuration block.

  • By default, NGINX compresses responses only with MIME type text/html

  • To compress responses with other MIME types, include the gzip_types directive and list the additional types

  • gzip_min_length directive. The default is 20 bytes (here adjusted to 1000):

  • By default, NGINX does not compress responses to proxied requests (requests that come from the proxy server). The fact that a request comes from a proxy server is determined by the presence of the Via header field in the request. To configure compression of these responses, use the gzip_proxied directive

    • compress responses only to requests that will not be cached on the proxy server
      • instruct NGINX to check the Cache-Control header field in a response and compress the response if the value is no-cache, no-store, or private
      • you must include the expired parameter to check the value of the Expires header field
      • parameters are set in the following example, along with the auth parameter, which checks for the presence of the Authorization header field (an authorized response is specific to the end user and is not typically cached):
    • gzip_proxied no-cache no-store private expired auth;

Optimization

  • Instead of compressing every object, configure NGINX to only compress large files and avoid the temptation to compress smaller files

Example

server {
    gzip on;
    gzip_types      text/plain application/xml;
    gzip_proxied    no-cache no-store private expired auth;
    gzip_min_length 1000;
}

gzip on;
gzip_vary on;
gzip_min_length 10240;
gzip_proxied expired no-cache no-store private auth;
gzip_types text/plain text/css text/xml text/javascript application/x-javascript application/xml;
gzip_disable "MSIE [1-6]\.";

=== Use

force https

if ($http_x_forwarded_proto = 'http'){
return 301 https://$host$request_uri;
}

rewrite logs

link: https://stackoverflow.com/questions/9900443/where-does-nginx-store-the-rewrite-log

If rewrite_log on; is used then the rewrite information will be logged to error_log at notice level. There is no separate log file.

rewrite_log on;
error_log logs/error.log notice;

return fixed response

location / {
    return 200 'gangnam style!';
    # because default content-type is application/octet-stream,
    # browser will offer to "save the file"...
    # if you want to see reply in browser, uncomment next line 
    # add_header Content-Type text/plain;
}

nginx update ip based on x-forwarded for

link: http://nginx.org/en/docs/http/ngx_http_realip_module.html#set_real_ip_from

  • This module is not built by default, it should be enabled with the –with-http_realip_module configuration parameter.
set_real_ip_from  192.168.1.0/24;
set_real_ip_from  192.168.2.1;
set_real_ip_from  2001:0db8::/32;
real_ip_header    X-Forwarded-For;
real_ip_recursive on;

check if module is enabled in nginx

nginx -V

redirect based on query string

link: https://serverfault.com/questions/811912/can-nginx-location-blocks-match-a-url-query-string

- request: GET /git/sample-repository/info/refs?service=git-receive-pack HTTP/1.1

server {
  #... common definitions such as server, root

  location / {
    error_page 418 = @queryone;
    error_page 419 = @querytwo;
    error_page 420 = @querythree;

    if ( $query_string = "service=git-receive-pack" ) { return 418; }
    if ( $args ~ "service=git-upload-pack" ) { return 419; }
    if ( $arg_somerandomfield = "somerandomvaluetomatch" ) { return 420; }

    # do the remaining stuff
    # ex: try_files $uri =404;

  }

  location @queryone {
    # do stuff when queryone matches
  }

  location @querytwo {
    # do stuff when querytwo matches
  }

  location @querythree {
    # do stuff when querythree matches
  }
}

block robots

location = /robots.txt { return 200 "User-agent: *\nDisallow: /\n"; }

restrict traffic

restrict traffic - basic auth

sudo htpasswd -c -b /etc/htpasswd cron cronuserpass 

  • auth ctx: http, server, location, limit_except
location /cron {
    auth_basic "cron"
    auth_basic_user_file /etc/htpasswd; 
    return 200 'you are running a cron';
}

restrict traffic - ip

location /cron {
    allow 10.0.0.0/16;
    deny all;
    return 200 'you are running a cron';
}

restrict traffic - user agent

if ($http_user_agent ~* YandexBot) {
    return 404;
}

=== Operators

Comment

# this is a comment

Comparison

  • =: If an equal sign is used, this block will be considered a match if the request URI exactly matches the location given.
  • ~: If a tilde modifier is present, this location will be interpreted as a case-sensitive regular expression match.
  • ~*: If a tilde and asterisk modifier is used, the location block will be interpreted as a case-insensitive regular expression match.
  • ^~: If a carat and tilde modifier is present, and if this block is selected as the best non-regular expression match, regular expression matching will not take place.

=== Mac

  • Docroot is: /usr/local/var/www
  • The default port has been set in /usr/local/etc/nginx/nginx.conf to 8080 so that nginx can run without sudo.
  • nginx will load all files in /usr/local/etc/nginx/servers/.
  • To have launchd start nginx now and restart at login: brew services start nginx
  • logs: /usr/local/var/log/nginx

=== API

— core

root

  • Syntax: root path;
  • Default: root html;
  • Context: http, server, location, if in location
  • eg
location /i/ {
    root foo
}
# request for "/i/bar will result in foo/i/bar

user [group]

desc: Set nginx user

server_name

default: “ “ params:

- " ": process without host

— http

include

desc: Like “source” in bash eg: /srv/www/foo.com/nginx.conf

log_format

keepalive_timeout

gzip [on | off];

desc: Compress files before sending it out

— server

server_name <names…>

default: “”

  • compares HOST header of http request
  • selects first one in nginx config file that matches order:
    • static name
    • wildcard at start
    • wildcard at end
    • reg expressions
  • if there is no match, use server block with matching listen directive marked as [default default_server]
  • first block with matching listen directive

access_log [ path | “off”];

listen ["default_server"]

What ports to listen to. If set to default server, will be used hostnames don’t match any particular host name.

— location

  • synposis: location optional_modifier location_match

  • parms:
    • optional_modifier
      • =: If an equal sign is used, this block will be considered a match if the request URI exactly matches the location given.
      • ~: If a tilde modifier is present, this location will be interpreted as a case-sensitive regular expression match.
      • ~*: If a tilde and asterisk modifier is used, the location block will be interpreted as a case-insensitive regular expression match.
      • ^~: If a carat and tilde modifier is present, and if this block is selected as the best non-regular expression match, regular expression matching will not take place.
  • examples
    • location sensitive regex: location ~ \.(jpe?g|png|gif|ico)$
      • match /tortoise.jpg, but not for /FLOWER.PNG

— return

desc: simplier version of rewrite. modify url specified in a server or location block

  • eg:
server {
    listen 80;
    listen 443 ssl;
    server_name www.old-name.com;
    return 301 $scheme://www.new-name.com$request_uri;
}

— rewrite

desc: modify url if it matches the regex

  • test for more complicated distinctions between URLs, capture elements in the original URL that don’t have corresponding NGINX variables, or change or add elements in the path

  • gotchas
    • can return only code 301 or 302. to return other codes, include return directive
    • doesn’t halt processing of request unless indicated by flag
    • if the original location block and the NGINX rewrite rules in it match the rewritten URL, NGINX can get into a loop
  • syntax: rewrite regex replacement [flag];

  • default: nil

  • context: server, location, if

  • params:
    • flag
      • last: stops processing the current set of ngx_http_rewrite_module directives and starts a search for a new location matching the changed URI;
  • example
server {
    ...
    # /download/bar1/media/bar2 -> /download/bar1/mp3/bar2.mp3 
    rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last;
    rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra  last;
    return  403;
    ...
}


— try_files

shortcuts

  • show file or 403
location /images {
    try_files $uri =403;
}

Table of contents


Copyright © 2020 Thence LLC