Nginx

Nginx is a high performance HTTP server, alternative to apache httpd.

Apache vs Nginx

htaccess

Not available

Rewrite Rules

Rewrite rules change part or all of a URL in a client request.

Example:

  • Tell the client the content is at a different address: e.g. domain name has changed
  • Forward requests to an application server

Apache Rule: .. code:

RewriteCond %{HTTP_HOST} example.org
RewriteRule (.*)         http://www.example.org$1

Nginx Conf ..code:

server {
    listen      80;
    server_name example.org;
    return      301 http://www.example.org$request_uri;
}

server {
    listen      80;
    server_name www.example.org;
    ...
}

return Directive

This is simpler, use where possible.

..code:

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

HTTP and HTTPs requests for: ‘’www.old-name.com’’ will result in a 301 redirect (Moved Permanently) to www.new-name.com with the same uri

Redirect returns: Syntax: return (301 | 302 | 303 | 307) url;

Other HTTP Status with return Optionally include a message Syntax: return (1xx | 2xx | 4xx | 5xx) [“text”]; Example: return 401 “Access denied because token is expired or invalid”;

Use error_page directive to return a more complex error page

Variables

$scheme = [http|https] $request_uri = Full URI including arguments

rewrite Directive

Permits more complex distinction between URLs The rewrite directive is like a return directive and decarled in a server or location block. Syntax: rewrite regex URL [flag]; rewrite can only return HTTP 301 or 302, to include more you need to use a rewrite with a return rewrite doesn’t stop NGINX’s processing, like return does

Example:

Match a URI starting ‘/download’ and including ‘/media/’ or ‘/audio/’ it then rewrites this this to /mp3/ and adds the appropriate extension .mp3 (audio) or .ra (media).

If no URL is matched return a 403

..code:

server {
    ...
    rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 last;
    rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra  last;
    return  403;
    ...
}

/download/cdn-west/media/file1 becomes /download/cdn-west/mp3/file1.mp3

Flags

You can add flags to the end of a rewrite rule, last is shown as such a flag, shown above.

last
Skip any subsequent rewrite directives in the current server/location block (make this the last).

try_files directive

Placed in a server or location block. Takes a list of one or more files and directories and a final URI. Directories are indicated by a trailing slash. Syntax: try_files file … uri;

location ~ /logatom/logs/.*/.*/httpaccess_.*$ {
#rewrite ^/logs/(.*) /$1;
#try_files $uri =404;
root /usr/cachelogic/log/traffic_logs/processed;
}