Difference between revisions of "Nginx Installation and Configuration"

From Biowikifarm Metawiki
Jump to: navigation, search
m (location: check order)
 
(27 intermediate revisions by 4 users not shown)
Line 3: Line 3:
 
* http://www.howtoforge.com/installing-nginx-with-php5-and-mysql-support-on-debian-lenny
 
* http://www.howtoforge.com/installing-nginx-with-php5-and-mysql-support-on-debian-lenny
 
* http://www.howtoforge.com/installing-php-5.3-nginx-and-php-fpm-on-ubuntu-debian
 
* http://www.howtoforge.com/installing-php-5.3-nginx-and-php-fpm-on-ubuntu-debian
* Sehr hilfreich für mediawiki: http://blog.bigdinosaur.org/mediawiki-on-nginx/
+
* Very helpful for mediawiki: http://blog.bigdinosaur.org/mediawiki-on-nginx/
 +
* Interesting and authoritative, but covers only single mediawiki in root, not clear how to modify: http://wiki.nginx.org/MediaWiki
 +
* Mediawiki, very useful mediawiki-config-generator: http://shorturls.redwerks.org/
 +
* Highly recommended: http://www.nginx-discovery.com/2011/04/day-45-location-regexp-or-no-regexp.html
 +
* nginx behaves differently with respect to output flushing than apache, perhaps a solution here: http://www.justincarmony.com/blog/2011/01/24/php-nginx-and-output-flushing/
  
'''Protocol of work done so far:'''
+
 
 +
__TOC__
 +
 
 +
== Installation ==
  
 
  sudo nano /etc/apt/sources.list
 
  sudo nano /etc/apt/sources.list
Line 17: Line 24:
 
  rm dotdeb.gpg
 
  rm dotdeb.gpg
  
Install:
+
Install nginx, fpm, new php:
 
  sudo apt-get update
 
  sudo apt-get update
  sudo apt-get install php5 php5-fpm php-pear php5-common php5-mcrypt php5-mysql php5-cli php5-gd
+
  sudo apt-get install php5 php5-fpm php-pear php5-common php5-mcrypt php5-mysql php5-cli php5-gd php5-curl php5-dev php5-imagick php5-imap php5-intl php5-pspell php5-recode php5-snmp php5-sqlite php5-tidy php5-xmlrpc
 +
sudo apt-get install libapache2-mod-php5 php5-apc
 
  sudo apt-get install nginx
 
  sudo apt-get install nginx
 +
 +
Apply "cgi.fix_pathinfo = 0;" in php.ini (security, avoid loading undesired php in a subfolder).
  
 
Change php-fpm configuration with:
 
Change php-fpm configuration with:
 
  sudo nano /etc/php5/fpm/php-fpm.conf
 
  sudo nano /etc/php5/fpm/php-fpm.conf
and mostly
+
and
 
  sudo nano /etc/php5/fpm/pool.d/www.conf
 
  sudo nano /etc/php5/fpm/pool.d/www.conf
 
setting:
 
setting:
Line 36: Line 46:
 
Change nginx configuration with:
 
Change nginx configuration with:
 
  sudo nano /etc/nginx/nginx.conf
 
  sudo nano /etc/nginx/nginx.conf
adding the settings for
+
adding various settings.
client_max_body_size 20M;
+
client_body_buffer_size 128k;
+
  
 
edit the default vhost config:
 
edit the default vhost config:
  cd /etc/nginx/sites-enabled; nano /etc/nginx/sites-available/default
+
  cd /etc/nginx/sites-enabled; nano /etc/nginx/sites-available/00_default
  
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
+
* If you are running your own domain, see "Virtual Hosts" below.
location ~ \.php$ {
+
* To create symlinks for further vhost files like "www.example.com" under sites-enabled:
# NOTE 1: You should have "cgi.fix_pathinfo = 0;" in php.ini to
+
ln -s /etc/nginx/sites-available/www.example.com /etc/nginx/sites-enabled/www.example.com
# prevent break-ins, else if non-existing file 123.txt/x.php is
+
# passed, php may execute 123.txt! (or even ".jpg", which may contain embedded php...)
+
# NOTE 2: the following also may prevent this, serving ONLY the file itself:
+
try_files $uri =404;
+
include fastcgi_params;
+
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
+
# TEST FILE: /var/www/phpinfo_1417869461139.php;
+
fastcgi_index index.php;
+
  
### NOT SURE WHETHER NECESSARY:
 
fastcgi_split_path_info ^(.+\.php)(/.+)$;
 
  
# With php5-cgi on 9001:
 
# fastcgi_pass 127.0.0.1:9001;
 
# With php5-fpm on 9000:
 
# fastcgi_pass  127.0.0.1:9000;
 
# With php5-fpm on sock (note that the listen directive
 
#  /etc/php5/fpm/pool.d/www.conf has to reflect this:
 
fastcgi_pass unix:/var/run/php5-fpm.sock;
 
}
 
  
NOTE: The security change "cgi.fix_pathinfo = 0;" in php.ini was applied on biowikifarm.
+
: NOTE: One failure we experienced was that we tested php with the phpinfo.php file, which, however, uses short php open tags. The default FPM-based php.ini in /etc/php5/fpm has short_open_tag = Off however. This initially and wrongly lead us to the conclusion that php was not working.
  
NOTE: One failure we experienced was that we tested php with the phpinfo.php file, which, however, uses short php open tags. The default FPM-based php.ini in /etc/php5/fpm has short_open_tag = Off however. This initially and wrongly lead us to the conclusion that php was not working.
+
: NOTE: for testing we used port 8880, which goes through bgbm (but not jki) firewalls.
  
 +
----
  
(To create symlinks for further vhost files like "www.example.com" under sites-enabled:
 
ln -s /etc/nginx/sites-available/www.example.com /etc/nginx/sites-enabled/www.example.com
 
)
 
  
 +
Restart apache, nginx and fpm (we still use apache for certain uses):
 +
sudo /usr/sbin/apache2ctl -k graceful && sudo service nginx restart && sudo service php5-fpm restart
 +
STOP:
 +
sudo /etc/init.d/php5-fpm stop; sudo /etc/init.d/nginx stop
  
'''NOT YET DONE OR CHECKED, our keys are elsewhere:'''
+
== Configuration: Locations and Rewrites ==
For ssl on port 443, copy and paste the entire vhost code into the bottom of the vhost file, change 'listen' to 443 and point to the ssl certs:
+
ssl on;
+
ssl_certificate /path/to/certificate/www.website.com.crt;
+
ssl_certificate_key /path/to/certificate_key/www.website.com.key;
+
  
 +
See for instance <code>/etc/nginx/sites-available/default</code>
 +
* http://wiki.nginx.org/HttpRewriteModule
 +
* http://wiki.nginx.org/HttpCoreModule
  
Restart php5-fpm and nginx:
+
=== Cheat sheet ===
''' sudo /etc/init.d/php5-fpm restart && sudo /etc/init.d/nginx restart'''
+
STOP:
+
sudo /etc/init.d/php5-fpm stop; sudo /etc/init.d/nginx stop
+
  
 +
==== location ====
  
 +
'''Syntax:'''
 +
{{Nginx docurl|location}} [ = | ^~ | ~ | ~* ] uri { ... }
 +
{{Nginx docurl|location}} @name { … }
 +
'''Context:''' server, location
 +
'''Check order:'''
 +
  (1) {{Nginx docurl|location}} = string-uri { … }  exact, identical match (''stop'' further searching)
 +
  (2) {{Nginx docurl|location}} ^~ string-uri { … }  match beginning with (''stop'' further searching)
 +
  (3) {{Nginx docurl|location}} ~  regex-uri { ''case sensitive'' }  ┬ ''executed in order of appearance''
 +
  (3) {{Nginx docurl|location}} ~* regex-uri { ''case '''in'''sensitive'' } ┘
 +
  (4) {{Nginx docurl|location}} string-uri { … }
  
----
+
The order in which location directives are checked is as follows:
 +
: (1) Directives with the "=" prefix that match the query exactly (literal string). If found, searching stops.
 +
: (2) All "^~" prefixed locations with conventional strings. If it matches, searching stops.
 +
: (3) Regular expressions, in the order they are defined in the configuration file.
 +
: (4) All remaining directives with conventional strings, “most specific“ strings are executed:
 +
<syntaxhighlight lang="text" line="true" style="margin-left:1.5em;">
 +
location /w/ { … }
 +
location /w/images/details/ { … }
 +
location /w/images/a/ { … }
 +
</syntaxhighlight>
 +
 
 +
<div class="pre-border-top-bottom-only pre-no-background">
 +
              Examples of requests:  “/”    “/documents/document.html”  “/documents/1.jpg”
 +
                                      │ “/index.html”  │  “/images/1.gif”      │
 +
location = / {                      ←─┘      │        │        │              │  ← rank check order (1): matches the query / '''only'''
 +
  [ configuration A ]                        │        │        │              │
 +
}                                            │        │        │              │
 +
location / {                                │        │        │              │  ← rank check order (4): matches any query
 +
  [ configuration B ]              ←────────┘        │        │              │    but regular expressions and any longer
 +
}                                                      │        │              │    conventional blocks will be matched first
 +
location /documents/ {                                │        │              │  ← rank check order (4)
 +
  [ configuration C ]              ←──────────────────┘        │              │
 +
}                                                                │              │
 +
location ^~ /images/ {                                          │              │  ← rank check order (2): matches any query ''beginning'' with /images/
 +
  [ configuration D ]              ←────────────────────────────┘              │    and halts searching, so regular expressions will not be checked.
 +
}                                                                              │
 +
location ~* \.(gif|jpg|jpeg)$ {                                                │  ← rank check order (3): matches any ''case insensitive'' request ending in gif, jpg, or jpeg
 +
  [ configuration E ]              ←───────────────────────────────────────────┘    except for those beginning with /images/ (=configuration D)
 +
}                                    (not to C, because regex is executed ''before'')
 +
</div>
 +
 
 +
==== rewrite, try_files ====
 +
 
 +
'''Syntax:'''
 +
{{Nginx docurl|rewrite}} regex replacement [flag];
 +
'''Context:''' server, location, if
 +
'''Check order rules:'''
 +
  * executed in order of appearance
 +
  * [flag] can terminate further processing of the directives
 +
    ├→ last → stops processing the current set of ngx_http_rewrite_module directives
 +
    │        and ''starts a search for a new location'' matching the changed URI;
 +
    ├→ break → stops processing the current set of ngx_http_rewrite_module directives as with the break directive;
 +
    ├→ redirect → returns a temporary redirect (302 code); used if a replacement string does not start with “http://” or “https://”.
 +
    └→ permanent → returns a permanent redirect (301 code)
 +
  * “http://” or “https://” begins the rewrite: the processing stops and the redirect is returned to a client
 +
 
 +
Examples (see also http://wiki.nginx.org/Pitfalls)
 +
<syntaxhighlight lang="apache" line="true" style="margin-left:1.5em;" highlight="8">
 +
location / {
 +
  # Redirect domain-only access (= no path given, w/o or with /) to default wiki:
 +
  # 302 → temporary redirect
 +
  # 301 → permanent redirect
 +
  return 301 "^[/]?$" /web/;
 +
}
 +
location ^~ /web/ {
 +
  try_files $uri $uri/ @do_wikipage; # if it fails try named location block @do_wikipage
 +
}
 +
location @do_wikipage {  # try as wiki page:
 +
  rewrite "^/web/?(.+)$" /w/index.php?title=$1&args redirect;  #(wiki reports 404 for non-existing pages! But can be created)
 +
}
 +
</syntaxhighlight>
 +
 
 +
===Virtual hosts===
 +
 
 +
Virtual host configurations are in /etc/nginx/sites-available
 +
They are linked from /etc/nginx/sites-enabled
 +
 
 +
The default configuration file (containing biowikifarm.net) is /etc/nginx/sites-available/00-default
 +
 
 +
This file is linked from /etc/nginx/sites-enabled/default
 +
 
 +
Each domain on biowikifarm (other than biowikifarm.net) has its own configuration file in sites-available.
 +
To create a new configuration, make a copy of default.dpkg-dist.
 +
To enable the domain, link it from sites-enabled.
 +
To test if the configuration is OK, run
 +
<syntaxhighlight lang="bash">
 +
sudo nginx -t
 +
sudo nginx -t -c /etc/nginx/nginx.conf # test a specific configuration file
 +
</syntaxhighlight>
 +
 
 +
Changes will take effect after you restart nginx.
 +
 
 +
The "old" configuration files (2014.12.05) are now in /etc/nginx/sites-available-backup
  
(TEMP: TESTING NOW ON port 8880, TEST URLs:
+
See also:
http://biowikifarm.net:8880/phpinfo_1417869461139.php
+
*[https://www.digitalocean.com/community/tutorials/how-to-set-up-nginx-server-blocks-virtual-hosts-on-ubuntu-14-04-lts Nginx Server Blocks]
http://biowikifarm.net:8880/metawiki/index.php?title=Upgrades_and_Changes&diff=0&oldid=3936
+
*[http://colorer.sourceforge.net/eclipsecolorer/ Eclipse colorer] open with->other->colorer editor
)
+
*[http://nginx.org/en/docs/ Nginx documentation]
 +
*[http://wiki.nginx.org/Configuration Nginx Configuration]
 +
*[http://wiki.nginx.org/Pitfalls Common Nginx configuration pitfalls]
 +
[[Category:Nginx]]

Latest revision as of 22:31, 7 February 2015

Based on


Installation

sudo nano /etc/apt/sources.list

add lines:

# necessary only for php-fpm, the php version for nginx:
deb http://packages.dotdeb.org stable all

Add the GnuPG key to your distribution:

wget http://www.dotdeb.org/dotdeb.gpg
cat dotdeb.gpg | sudo apt-key add -
rm dotdeb.gpg

Install nginx, fpm, new php:

sudo apt-get update
sudo apt-get install php5 php5-fpm php-pear php5-common php5-mcrypt php5-mysql php5-cli php5-gd php5-curl php5-dev php5-imagick php5-imap php5-intl php5-pspell php5-recode php5-snmp php5-sqlite php5-tidy php5-xmlrpc
sudo apt-get install libapache2-mod-php5 php5-apc
sudo apt-get install nginx

Apply "cgi.fix_pathinfo = 0;" in php.ini (security, avoid loading undesired php in a subfolder).

Change php-fpm configuration with:

sudo nano /etc/php5/fpm/php-fpm.conf

and

sudo nano /etc/php5/fpm/pool.d/www.conf

setting:

pm.max_children = 25
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 10
pm.max_requests = 1500
request_terminate_timeout = 450s

Change nginx configuration with:

sudo nano /etc/nginx/nginx.conf

adding various settings.

edit the default vhost config:

cd /etc/nginx/sites-enabled; nano /etc/nginx/sites-available/00_default
  • If you are running your own domain, see "Virtual Hosts" below.
  • To create symlinks for further vhost files like "www.example.com" under sites-enabled:

ln -s /etc/nginx/sites-available/www.example.com /etc/nginx/sites-enabled/www.example.com


NOTE: One failure we experienced was that we tested php with the phpinfo.php file, which, however, uses short php open tags. The default FPM-based php.ini in /etc/php5/fpm has short_open_tag = Off however. This initially and wrongly lead us to the conclusion that php was not working.
NOTE: for testing we used port 8880, which goes through bgbm (but not jki) firewalls.


Restart apache, nginx and fpm (we still use apache for certain uses):

sudo /usr/sbin/apache2ctl -k graceful && sudo service nginx restart && sudo service php5-fpm restart

STOP:

sudo /etc/init.d/php5-fpm stop; sudo /etc/init.d/nginx stop

Configuration: Locations and Rewrites

See for instance /etc/nginx/sites-available/default

Cheat sheet

location

Syntax:
location [ = | ^~ | ~ | ~* ] uri { ... }
location @name { … }
Context: server, location
Check order:
  (1) location = string-uri { … }   exact, identical match (stop further searching)
  (2) location ^~ string-uri { … }  match beginning with (stop further searching)
  (3) location ~  regex-uri { case sensitive }   ┬ executed in order of appearance
  (3) location ~* regex-uri { case insensitive } ┘
  (4) location string-uri { … }

The order in which location directives are checked is as follows:

(1) Directives with the "=" prefix that match the query exactly (literal string). If found, searching stops.
(2) All "^~" prefixed locations with conventional strings. If it matches, searching stops.
(3) Regular expressions, in the order they are defined in the configuration file.
(4) All remaining directives with conventional strings, “most specific“ strings are executed:
1 location /w/ { … }
2 location /w/images/details/ { … }
3 location /w/images/a/ { … }
             Examples of requests:   “/”     “/documents/document.html”   “/documents/1.jpg”
                                      │ “/index.html”  │  “/images/1.gif”       │
location = / {                      ←─┘      │         │         │              │  ← rank check order (1): matches the query / only
  [ configuration A ]                        │         │         │              │
}                                            │         │         │              │
location / {                                 │         │         │              │  ← rank check order (4): matches any query
  [ configuration B ]               ←────────┘         │         │              │    but regular expressions and any longer
}                                                      │         │              │    conventional blocks will be matched first
location /documents/ {                                 │         │              │  ← rank check order (4)
  [ configuration C ]               ←──────────────────┘         │              │
}                                                                │              │
location ^~ /images/ {                                           │              │  ← rank check order (2): matches any query beginning with /images/
  [ configuration D ]               ←────────────────────────────┘              │    and halts searching, so regular expressions will not be checked.
}                                                                               │
location ~* \.(gif|jpg|jpeg)$ {                                                 │  ← rank check order (3): matches any case insensitive request ending in gif, jpg, or jpeg
  [ configuration E ]               ←───────────────────────────────────────────┘    except for those beginning with /images/ (=configuration D)
}                                    (not to C, because regex is executed before)

rewrite, try_files

Syntax:
rewrite regex replacement [flag];
Context: server, location, if
Check order rules:
 * executed in order of appearance
 * [flag] can terminate further processing of the directives
    ├→ last → stops processing the current set of ngx_http_rewrite_module directives 
    │         and starts a search for a new location matching the changed URI;
    ├→ break → stops processing the current set of ngx_http_rewrite_module directives as with the break directive;
    ├→ redirect → returns a temporary redirect (302 code); used if a replacement string does not start with “http://” or “https://”.
    └→ permanent → returns a permanent redirect (301 code)
 * “http://” or “https://” begins the rewrite: the processing stops and the redirect is returned to a client

Examples (see also http://wiki.nginx.org/Pitfalls)

 1 location / {
 2   # Redirect domain-only access (= no path given, w/o or with /) to default wiki:
 3   # 302 → temporary redirect
 4   # 301 → permanent redirect
 5   return 301 "^[/]?$" /web/;
 6 }
 7 location ^~ /web/ {
 8   try_files $uri $uri/ @do_wikipage; # if it fails try named location block @do_wikipage
 9 }
10 location @do_wikipage {   # try as wiki page:
11   rewrite "^/web/?(.+)$" /w/index.php?title=$1&args redirect;  #(wiki reports 404 for non-existing pages! But can be created)
12 }

Virtual hosts

Virtual host configurations are in /etc/nginx/sites-available They are linked from /etc/nginx/sites-enabled

The default configuration file (containing biowikifarm.net) is /etc/nginx/sites-available/00-default

This file is linked from /etc/nginx/sites-enabled/default

Each domain on biowikifarm (other than biowikifarm.net) has its own configuration file in sites-available. To create a new configuration, make a copy of default.dpkg-dist. To enable the domain, link it from sites-enabled. To test if the configuration is OK, run

sudo nginx -t
sudo nginx -t -c /etc/nginx/nginx.conf # test a specific configuration file

Changes will take effect after you restart nginx.

The "old" configuration files (2014.12.05) are now in /etc/nginx/sites-available-backup

See also: