際際滷

際際滷Share a Scribd company logo
NginX - Good practices, tips
and advanced techniques
Claudio Filho
<claudio.鍖lho@locaweb.com.br>
About me
+14 years experience with Linux/Unix.
Technical Operations Leader at Locaweb.
I can handle myself in different languages such as
Python, Perl, PHP, Bash, Lua, C and I'm learning
Ruby.
USF4 Player (PSN ID: but3k4 or piupiu_monstro).
A brief description about NginX
NginX (pronounced "engine X) is an
OpenSource HTTP and reverse proxy server,
a mail proxy server, and a load balancing
server.
Currently it is the second most popular web
server on the Internet.
Good Practices
NginX is 鍖exible, it allows to do the same thing
in different ways, but, good practices can save
resources and increase the performance
(such as good programming techniques).
try_鍖les is basically a replacement for the typical mod_rewrite
style 鍖le/directory existence check.
If possible, avoid to use if (-f ), it is a bad practice(according
to author of NginX)., ex:
bad:
if (-f $request_filename) {
.
}
good:
location / {
try_files $uri $uri/ = 404;
}
try_鍖les instead of if
Using the return directive we can completely
avoid evaluation of regular expression.
bad:
rewrite ^/(.*)$ http://domain.com/$1 permanent;
also bad:
rewrite ^ http://domain.com$request_uri? permanent;
good:
return 301 http://domain.com$request_uri;
return instead of rewrite
Avoid proxy everything. The try_鍖les directive tries 鍖les in a speci鍖c
order. This means that NginX can 鍖rst look for a number of static
鍖les to serve and if not found move on to a user de鍖ned fallback.
proxy everything
bad:
location / {
proxy_pass http://upstream_servers;
}
good:
location / {
try_files $uri $uri/ @proxy;
}
location @proxy {
proxy_pass http://upstream_servers;
}
You can include any con鍖guration 鍖les for what ever
purpose you want. The include directive also supports
鍖lename globbing. The examples below show how the
nginx.conf 鍖le already uses includes by default:
include 鍖les
include /etc/nginx/conf.d/*.conf;
or
include conf.d/*.conf;
Tips
NginX has dozen of modules (native or third-
party), each module has a lot of directive,
each directive has its own peculiarities.
core module
core module has a lot of directives, among of them, there are
interested directives:
http2
location
limit_rate
error_page
resolver
try_鍖les
http rewrite module
This module makes it possible to change URI using Perl
Compatible Regular Expressions (PCRE), and to redirect and
select con鍖guration depending on variables. This cycle can be
repeated up to 10 times, after which Nginx returns a 500 error.
server_name ~^(?P<subdomain>[wd-]+.)?(?P<domain>[wd-]+).(?P<cctld>[w.]+)$;
set $docroot "default";
if ($domain) {
set $docroot $domain;
}
root /srv/$docroot/www;
gzip log 鍖les
If you want, you can specify compression of the log 鍖les. If the gzip
parameter is used, then the buffered data will be compressed before
writing to the 鍖le.
Since the data is compressed in atomic blocks, the log 鍖le can be
decompressed or read by "zcat" at any time.
format:
access_log location format gzip;
ex:
access_log /var/log/nginx/access.log.gz combined gzip;
http map module
The http map module enable to create variables whose values
depend on values of other variables. You can create new
variable whose value depends on values of one or more of the
source variables speci鍖ed in the 鍖rst parameter.
map $http_user_agent $bad_user_agent {
default 0;
~*wget 1;
~*curl 1;
~*libwww-perl 1;
~*python-urllib 1;
~*PycURL 1;
}
http echo module
This module wraps lots of Nginx internal APIs for
streaming input and output, parallel/sequential
subrequests, timers and sleeping, as well as various
meta data accessing.
location /echo {
default_type text/html;
echo -n "<html>n<head><title>echo</title></head>n<body><h1>echo</h1></body>n</html>
n";
}
http lua module
This module embeds Lua, via the standard Lua 5.1
interpreter or LuaJIT 2.0/2.1, into Nginx and by leveraging
Nginx's subrequests, allows the integration of the powerful
Lua threads (Lua coroutines) into the Nginx event model.
location /lua {
default_type text/plain;
content_by_lua nginx.say(hello, world!);
}
http perl module
The ngx_http_perl_module module is used to
implement location and variable handlers in
Perl and insert Perl calls into SSI.
http Live Streaming (HLS) module
The ngx_http_hls_module module provides HTTP Live
Streaming (HLS) server-side support for MP4 and MOV media
鍖les. Such 鍖les typically have the .mp4, .m4v, .m4a, .mov, or .qt
鍖lename extensions. The module supports H.264 video codec,
AAC and MP3 audio codecs.
http://www.claudioborges.org/sf4.mp4.m3u8?offset=1.000&start=1.000&end=2.200
http://www.claudioborges.org/sf4.mp4.m3u8?len=8.000
http://www.claudioborges.org/sf4.mp4.ts?start=1.000&end=2.200
third-party modules
These modules are not of鍖cially supported and may not
be compatible across versions of Nginx. If you check this
(http://wiki.nginx.org/3rdPartyModules) you can 鍖nd
interested things. Enjoy at your own risk.
To compile a third-party module, from the Nginx source
directory, type:
./configure --add-module=/path/to/module1/source 
--add-module=/path/to/module2/source
Advanced techniques
NginX is a powerful web server with a lot of
features. But, it has a few limitations. For
example, it doesnt have nested ifs, but, you
can use a different way to do that.
nested if statement - part 1
Like I said, NginX doesn't allow nested if
statements, for example, you can't do
something like:
if ($http_refer ~* .*claudioborges.*" && $args ~* execute) {
rewrite ^/things$ /another_thing break;
}
nested if statement part - 2
But, you can do using a different way:
set $result "";
if ($http_refer ~* ".*claudioborges.*") {
set $result 1;
}
if ($args ~* "execute") {
set $result 2;
}
if ($result = 2) {
rewrite ^/things$ /another_thing break;
}
Dynamic virtual host
You can use dynamic virtual hosts in NginX. I mean, you can
create just one 鍖le for many websites. It works similar to Apache
mod_vhost_alias.
server {
listen 80;
server_name ~^(?P<subdomain>[wd-]+.)?(?P<domain>[wd-]+).(?P<cctld>[w.]+)$;
index index.html;
set $docroot default";
if ($domain) {
set $docroot $domain;
}
root /srv/$docroot/www;
location / {
try_files $uri $uri/ =404;
}
access_log /var/log/nginx/$domain-access.log main;
error_log /var/log/nginx/error.log;
}
HTTP and HTTPS in the same
virtual host - part 1
Unlike Apache, NginX allows to use the same
virtual host for both HTTP and HTTPS. Its
con鍖guration is pretty easy and using it avoid
duplicate con鍖gurations.
HTTP and HTTPS in the same
virtual host - part 2
To do that, you need to merge the HTTP and HTTPS virtual host 鍖le
in a unique 鍖le. The only detail is: You need to omit the "SSL on"
option. This directive in modern versions is thus discouraged.
The example below shows an unique virtual host that handles both
HTTP and HTTPS requests:
server {
listen 80;
listen 443 ssl http2;
server_name www.example.com;
ssl_certificate www.example.com.crt;
ssl_certificate_key www.example.com.key;
...
}
References
http://nginx.org
http://wiki.nginx.org/Pitfalls
http://wiki.nginx.org/IfIsEvil
http://wiki.nginx.org/3rdPartyModules
http://w3techs.com/technologies/cross/
web_server/ranking
Thanks for you attention!
Any questions?
Claudio Filho
<claudio.鍖lho@locaweb.com.br>
@but3k4
http://www.claudioborges.org
https://github.com/but3k4

More Related Content

NginX - good practices, tips and advanced techniques

  • 1. NginX - Good practices, tips and advanced techniques Claudio Filho <claudio.鍖lho@locaweb.com.br>
  • 2. About me +14 years experience with Linux/Unix. Technical Operations Leader at Locaweb. I can handle myself in different languages such as Python, Perl, PHP, Bash, Lua, C and I'm learning Ruby. USF4 Player (PSN ID: but3k4 or piupiu_monstro).
  • 3. A brief description about NginX NginX (pronounced "engine X) is an OpenSource HTTP and reverse proxy server, a mail proxy server, and a load balancing server. Currently it is the second most popular web server on the Internet.
  • 4. Good Practices NginX is 鍖exible, it allows to do the same thing in different ways, but, good practices can save resources and increase the performance (such as good programming techniques).
  • 5. try_鍖les is basically a replacement for the typical mod_rewrite style 鍖le/directory existence check. If possible, avoid to use if (-f ), it is a bad practice(according to author of NginX)., ex: bad: if (-f $request_filename) { . } good: location / { try_files $uri $uri/ = 404; } try_鍖les instead of if
  • 6. Using the return directive we can completely avoid evaluation of regular expression. bad: rewrite ^/(.*)$ http://domain.com/$1 permanent; also bad: rewrite ^ http://domain.com$request_uri? permanent; good: return 301 http://domain.com$request_uri; return instead of rewrite
  • 7. Avoid proxy everything. The try_鍖les directive tries 鍖les in a speci鍖c order. This means that NginX can 鍖rst look for a number of static 鍖les to serve and if not found move on to a user de鍖ned fallback. proxy everything bad: location / { proxy_pass http://upstream_servers; } good: location / { try_files $uri $uri/ @proxy; } location @proxy { proxy_pass http://upstream_servers; }
  • 8. You can include any con鍖guration 鍖les for what ever purpose you want. The include directive also supports 鍖lename globbing. The examples below show how the nginx.conf 鍖le already uses includes by default: include 鍖les include /etc/nginx/conf.d/*.conf; or include conf.d/*.conf;
  • 9. Tips NginX has dozen of modules (native or third- party), each module has a lot of directive, each directive has its own peculiarities.
  • 10. core module core module has a lot of directives, among of them, there are interested directives: http2 location limit_rate error_page resolver try_鍖les
  • 11. http rewrite module This module makes it possible to change URI using Perl Compatible Regular Expressions (PCRE), and to redirect and select con鍖guration depending on variables. This cycle can be repeated up to 10 times, after which Nginx returns a 500 error. server_name ~^(?P<subdomain>[wd-]+.)?(?P<domain>[wd-]+).(?P<cctld>[w.]+)$; set $docroot "default"; if ($domain) { set $docroot $domain; } root /srv/$docroot/www;
  • 12. gzip log 鍖les If you want, you can specify compression of the log 鍖les. If the gzip parameter is used, then the buffered data will be compressed before writing to the 鍖le. Since the data is compressed in atomic blocks, the log 鍖le can be decompressed or read by "zcat" at any time. format: access_log location format gzip; ex: access_log /var/log/nginx/access.log.gz combined gzip;
  • 13. http map module The http map module enable to create variables whose values depend on values of other variables. You can create new variable whose value depends on values of one or more of the source variables speci鍖ed in the 鍖rst parameter. map $http_user_agent $bad_user_agent { default 0; ~*wget 1; ~*curl 1; ~*libwww-perl 1; ~*python-urllib 1; ~*PycURL 1; }
  • 14. http echo module This module wraps lots of Nginx internal APIs for streaming input and output, parallel/sequential subrequests, timers and sleeping, as well as various meta data accessing. location /echo { default_type text/html; echo -n "<html>n<head><title>echo</title></head>n<body><h1>echo</h1></body>n</html> n"; }
  • 15. http lua module This module embeds Lua, via the standard Lua 5.1 interpreter or LuaJIT 2.0/2.1, into Nginx and by leveraging Nginx's subrequests, allows the integration of the powerful Lua threads (Lua coroutines) into the Nginx event model. location /lua { default_type text/plain; content_by_lua nginx.say(hello, world!); }
  • 16. http perl module The ngx_http_perl_module module is used to implement location and variable handlers in Perl and insert Perl calls into SSI.
  • 17. http Live Streaming (HLS) module The ngx_http_hls_module module provides HTTP Live Streaming (HLS) server-side support for MP4 and MOV media 鍖les. Such 鍖les typically have the .mp4, .m4v, .m4a, .mov, or .qt 鍖lename extensions. The module supports H.264 video codec, AAC and MP3 audio codecs. http://www.claudioborges.org/sf4.mp4.m3u8?offset=1.000&start=1.000&end=2.200 http://www.claudioborges.org/sf4.mp4.m3u8?len=8.000 http://www.claudioborges.org/sf4.mp4.ts?start=1.000&end=2.200
  • 18. third-party modules These modules are not of鍖cially supported and may not be compatible across versions of Nginx. If you check this (http://wiki.nginx.org/3rdPartyModules) you can 鍖nd interested things. Enjoy at your own risk. To compile a third-party module, from the Nginx source directory, type: ./configure --add-module=/path/to/module1/source --add-module=/path/to/module2/source
  • 19. Advanced techniques NginX is a powerful web server with a lot of features. But, it has a few limitations. For example, it doesnt have nested ifs, but, you can use a different way to do that.
  • 20. nested if statement - part 1 Like I said, NginX doesn't allow nested if statements, for example, you can't do something like: if ($http_refer ~* .*claudioborges.*" && $args ~* execute) { rewrite ^/things$ /another_thing break; }
  • 21. nested if statement part - 2 But, you can do using a different way: set $result ""; if ($http_refer ~* ".*claudioborges.*") { set $result 1; } if ($args ~* "execute") { set $result 2; } if ($result = 2) { rewrite ^/things$ /another_thing break; }
  • 22. Dynamic virtual host You can use dynamic virtual hosts in NginX. I mean, you can create just one 鍖le for many websites. It works similar to Apache mod_vhost_alias. server { listen 80; server_name ~^(?P<subdomain>[wd-]+.)?(?P<domain>[wd-]+).(?P<cctld>[w.]+)$; index index.html; set $docroot default"; if ($domain) { set $docroot $domain; } root /srv/$docroot/www; location / { try_files $uri $uri/ =404; } access_log /var/log/nginx/$domain-access.log main; error_log /var/log/nginx/error.log; }
  • 23. HTTP and HTTPS in the same virtual host - part 1 Unlike Apache, NginX allows to use the same virtual host for both HTTP and HTTPS. Its con鍖guration is pretty easy and using it avoid duplicate con鍖gurations.
  • 24. HTTP and HTTPS in the same virtual host - part 2 To do that, you need to merge the HTTP and HTTPS virtual host 鍖le in a unique 鍖le. The only detail is: You need to omit the "SSL on" option. This directive in modern versions is thus discouraged. The example below shows an unique virtual host that handles both HTTP and HTTPS requests: server { listen 80; listen 443 ssl http2; server_name www.example.com; ssl_certificate www.example.com.crt; ssl_certificate_key www.example.com.key; ... }
  • 26. Thanks for you attention! Any questions? Claudio Filho <claudio.鍖lho@locaweb.com.br> @but3k4 http://www.claudioborges.org https://github.com/but3k4