Nginx (pronunciato “motore x”) è un libero, open source, ad alte prestazioni HTTP server. Nginx è noto per la sua stabilità, ricco set di funzionalità, semplice configurazione e basso consumo di risorse.Questo tutorial Mostra come è possibile installare Nginx su un server CentOS 6.0 con supporto per PHP5 (attraverso PHP-FPM) e MySQL.
Io non rilasciano alcuna garanzia che questo funziona per voi!
1 Nota preliminare
In questo tutorial io uso il nome host Server1 con l’ indirizzo IP 192.168.0.100. Queste impostazioni potrebbero differire per te, quindi devi sostituirli ove opportuno.
2 Abilitazione repository aggiuntivi
php-fpm non è disponibile dai repository ufficiali di CentOS, ma dal repository RPM Remi che a sua volta dipende il repository EPEL; possiamo abilitare entrambi i repository come segue:
rpm --import https://fedoraproject.org/static/0608B895.txt
rpm -ivh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-5.noarch.rpm
rpm --import http://rpms.famillecollet.com/RPM-GPG-KEY-remi
rpm -ivh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
yum install yum-priorities
Modificare /etc/yum.repos.d/epel.repo…
vi /etc/yum.repos.d/epel.repo
… e aggiungere la riga priorità = 10 alla sezione [epel] :
[epel] name=Extra Packages for Enterprise Linux 6 - $basearch #baseurl=http://download.fedoraproject.org/pub/epel/6/$basearch mirrorlist=https://mirrors.fedoraproject.org/metalink?repo=epel-6&arch=$basearch failovermethod=priority enabled=1 priority=10 gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6 [...] |
Poi fare lo stesso per la sezione [remi] in /etc/yum.repos.d/remi.repo, oltre a modificare abilitato 1:
vi /etc/yum.repos.d/remi.repo
[remi] name=Les RPM de remi pour Enterprise Linux $releasever - $basearch #baseurl=http://rpms.famillecollet.com/enterprise/$releasever/remi/$basearch/ mirrorlist=http://rpms.famillecollet.com/enterprise/$releasever/remi/mirror enabled=1 priority=10 gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi failovermethod=priority [remi-test] name=Les RPM de remi en test pour Enterprise Linux $releasever - $basearch #baseurl=http://rpms.famillecollet.com/enterprise/$releasever/test/$basearch/ mirrorlist=http://rpms.famillecollet.com/enterprise/$releasever/test/mirror enabled=0 gpgcheck=1 gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-remi |
3 l’installazione di MySQL 5
Prima installiamo MySQL 5 come questo:
yum install mysql mysql-server
Poi creiamo i collegamenti di avvio del sistema per MySQL (in modo che MySQL si avvia automaticamente ogni volta che il sistema si avvia) e avviare il server MySQL:
chkconfig --levels 235 mysqld on
/etc/init.d/mysqld start
Ora verifica che la rete è abilitata. Correre
netstat -tap | grep mysql
Dovrebbe mostrare qualcosa come questo:
[root@server1 ~]# netstat -tap | grep mysql
tcp 0 0 *:mysql *:* LISTEN 2302/mysqld
[root@server1 ~]#
Se così non fosse, modificare /etc/my.cnf e commentare l’ opzione skip-networking:
vi /etc/my.cnf
[...] #skip-networking [...] |
e riavviare il server MySQL:
/etc/init.d/mysqld restart
Correre
mysql_secure_installation
per impostare una password per l’utente root (altrimenti chiunque può accedere al database MySQL!):
[root@server1 ~] # mysql_secure_installation
Nota: In esecuzione di tutte le parti di questo SCRIPT è consigliato per tutti MySQL
SERVER IN USO IN PRODUZIONE! SI PREGA DI LEGGERE ATTENTAMENTE OGNI PASSO!
Al fine di accedere a MySQL per fissarlo, avremo bisogno della corrente
password per l’utente root. Se hai appena installato MySQL, e
non hai impostato la password di root, ancora, la password sarà vuota,
quindi basta premere Immettere qui.
Enter current password for root (enter for none): <– ENTER
OK, successfully used password, moving on…
Setting the root password ensures that nobody can log into the MySQL
root user without the proper authorisation.
Set root password? [Y/n] <– ENTER
New password: <– yourrootsqlpassword
Re-enter new password: <– yourrootsqlpassword
Password updated successfully!
Reloading privilege tables..
… Success!
By default, a MySQL installation has an anonymous user, allowing anyone
to log into MySQL without having to have a user account created for
them. This is intended only for testing, and to make the installation
go a bit smoother. You should remove them before moving into a
production environment.
Remove anonymous users? [Y/n] <– ENTER
… Success!
Normally, root should only be allowed to connect from ‘localhost’. This
ensures that someone cannot guess at the root password from the network.
Disallow root login remotely? [Y/n] <– ENTER
… Success!
By default, MySQL comes with a database named ‘test’ that anyone can
access. This is also intended only for testing, and should be removed
before moving into a production environment.
Remove test database and access to it? [Y/n] <– ENTER
– Dropping test database…
… Success!
– Removing privileges on test database…
… Success!
Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.
Reload privilege tables now? [Y/n] <– ENTER
… Success!
Cleaning up…
All done! If you’ve completed all of the above steps, your MySQL
installation should now be secure.
Thanks for using MySQL!
[root@server1 ~]#
4 Installing Nginx
Nginx is available as a package for CentOS 6.0 (from EPEL) which we can install as follows:
yum install nginx
Then we create the system startup links for nginx and start it:
chkconfig --levels 235 nginx on
/etc/init.d/nginx start
Type in your web server’s IP address or hostname into a browser (e.g. http://192.168.0.100), and you should see the nginx welcome page:
5 installare PHP5
Possiamo fare PHP5 lavorare in nginx con PHP-FPM (PHP-FPM (FastCGI Process Manager) è un’implementazione alternativa di PHP FastCGI con alcune funzionalità aggiuntive utili per i siti di qualsiasi dimensioni, soprattutto più affollati siti). Possiamo installare php-fpm insieme aphp-cli e alcuni moduli PHP5 come php-mysql che è necessario se si desidera utilizzare MySQL dagli script PHP come segue:
yum install php-fpm php-cli php-mysql php-gd php-imap php-ldap php-odbc php-pear php-xml php-xmlrpc php-eaccelerator php-magickwand php-magpierss php-mbstring php-mcrypt php-mssql php-shout php-snmp php-soap php-tidy
Quindi aprire /etc/php.ini e impostare cgi.fix_pathinfo=0:
vi /etc/php.ini
[...] ; cgi.fix_pathinfo provides *real* PATH_INFO/PATH_TRANSLATED support for CGI. PHP's ; previous behaviour was to set PATH_TRANSLATED to SCRIPT_FILENAME, and to not grok ; what PATH_INFO is. For more information on PATH_INFO, see the cgi specs. Setting ; this to 1 will cause PHP CGI to fix its paths to conform to the spec. A setting ; of zero causes PHP to behave as before. Default is 1. You should fix your scripts ; to use SCRIPT_FILENAME rather than PATH_TRANSLATED. ; http://www.php.net/manual/en/ini.core.php#ini.cgi.fix-pathinfo cgi.fix_pathinfo=0 [...] |
(Si prega di leggere http://wiki.nginx.org/Pitfalls per scoprire perché si dovrebbe fare questo.)
In aggiunta a ciò, al fine di evitare errori come
[08-Aug-2011 18:07:08] PHP Warning: phpinfo(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Europe/Berlin' for 'CEST/2.0/DST' instead in /usr/share/nginx/html/info.php on line 2
… in var/log/php-fpm/www-error.log quando si chiama uno script PHP nel tuo browser, è necessario impostare date.timezone in /etc/php.ini:
[...] [Date] ; Defines the default timezone used by the date functions ; http://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone date.timezone = "Europe/Berlin" [...] |
Può scoprire il fuso orario corretto per il sistema eseguendo:
cat /etc/sysconfig/clock
[root@server1 nginx]# cat /etc/sysconfig/clock
ZONE="Europe/Berlin"
[root@server1 nginx]#
Successivamente creare i collegamenti di avvio del sistema per php-fpm e avviarlo:
chkconfig --levels 235 php-fpm on
/etc/init.d/php-fpm start
PHP-FPM è un processo del daemon (con l’init script /etc/init.d/php-fpm) che esegue un server FastCGI sulla porta 9000.
6 Configurare nginx
La configurazione di nginx è in /etc/nginx/nginx.conf. che apriamo ora:
vi /etc/nginx/nginx.conf
La configurazione è facile da capire (si può saperne di più qui: http://wiki.codemongers.com/NginxFullExample e qui: http://wiki.codemongers.com/NginxFullExample2)
Prima (questo è facoltativo) è possibile aumentare il numero di processi di lavoro e impostare il keepalive_timeout su un valore ragionevole:
[...] worker_processes 5; [...] keepalive_timeout 2; [...] |
Gli host virtuali sono definiti in contenitori server {} . Modifichiamo il vhost predefinito (in /etc/nginx/nginx.conf. pure) come segue:
[...] server { listen 80; server_name _; #charset koi8-r; #access_log logs/host.access.log main; location / { root /usr/share/nginx/html; index index.php index.html index.htm; } error_page 404 /404.html; location = /404.html { root /usr/share/nginx/html; } # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } # proxy the PHP scripts to Apache listening on 127.0.0.1:80 # #location ~ \.php$ { # proxy_pass http://127.0.0.1; #} # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php$ { root /usr/share/nginx/html; try_files $uri =404; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } # deny access to .htaccess files, if Apache's document root # concurs with nginx's one # location ~ /\.ht { deny all; } } [...] |
nome_server _; Questo rende un vhost catchall predefinito (naturalmente, è possibile anche specificare un nome host qui come www.example.com).
Nella posizione / parte, ho aggiunto index. php per la riga di Indice . /usr/share/nginx/html radice; significa che la radice del documento è la directory /usr/share/nginx/html.
La parte importante per PHP è la posizione ~ {} \.php$ strofa. Decommentarla per attivarla. Modificare la riga di radice alla radice del documento del sito web (es. radice /usr/share/nginx/html;). Si prega di assicurarsi che modifichi la linea di fastcgi_param a fastcgi_param SCRIPT_FILENAME $document_root$ fastcgi_script_name; perché altrimenti l’interprete PHP non troverà lo script PHP che si chiama nel tuo browser ($ DOCUMENT_ROOT si traduce in /usr/share/nginx/html , perché questo è ciò che abbiamo creato come nostra radice del documento).
PHP-FPM è in ascolto sulla porta 9000 su 127.0.0.1 per impostazione predefinita, pertanto diciamo nginx per connettersi a 127.0.0.1:9000 con la linea fastcgi_pass 127.0.0.1:9000;. È anche possibile fare PHP-FPM utilizzare un socket Unix – mi limiterò a descrivere questo nel capitolo 7.
Ora salvare il file e riavviare nginx:
/etc/init.d/nginx restart
Ora creare il seguente file PHP nel documento radice /usr/share/nginx/html…
vi /usr/share/nginx/html/info.php
<?php phpinfo(); ?> |
Ora noi chiamiamo quel file in un browser (ad esempio http://192.168.0.100/info.php):
Come vedete, PHP5 sta lavorando, e sta funzionando attraverso FPM/FastCGI, come mostrato nella riga Server API . Se si scorre più in basso, vedrete tutti i moduli che sono già abilitati in PHP5, compreso il modulo di MySQL:
7 fare PHP-FPM uso un Socket Unix
Per impostazione predefinita PHP-FPM è in ascolto sulla porta 9000 su 127.0.0.1. È anche possibile fare PHP-FPM utilizzare un socket Unix che evita l’overhead TCP. Per effettuare questa operazione, aprire /etc/php-fpm.d/www.conf…
vi /etc/php-fpm.d/www.conf
… e fare la linea Ascolta il seguente aspetto:
[...] ;listen = 127.0.0.1:9000 listen = /tmp/php5-fpm.sock [...] |
Quindi riavviare PHP-FPM:
/etc/init.d/php-fpm restart
Poi andate attraverso la configurazione di nginx e tutti i tuo vhost e modificare la linea fastcgi_pass 127.0.0.1:9000;fastcgi_pass unix:/tmp/php5-fpm.sock;ad esempio come questo:
vi /etc/nginx/nginx.conf
[...] location ~ \.php$ { root /usr/share/nginx/html; try_files $uri =404; fastcgi_pass unix:/tmp/php5-fpm.sock; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } [...] |
Infine riavviare nginx:
/etc/init.d/nginx restart
8 links
- Nginx: http://nginx.org/
- Nginx Wiki: http://wiki.nginx.org/
- PHP: http://www.php.net/
- PHP-FPM: http://php-fpm.org/
- MySQL: http://www.mysql.com/
- CentOS: http://www.centos.org/