Installer son propre serveur web (part.4)

Publié par Th. Barrault dans: Computing | HowTo | Techniques informatiques

Le 11 juin 2009, modifié le 14 juin 2009 à 15 h 33 min, 553 visites

 

Installation et administration d’un serveur WEB sous FREEBSD

 

Ce billet fait suite au billet précédent Installer son propre serveur web (part.3)

 
Chapitres « Installer son propre serveur web »

 

Préprocesseur Hypertext PHP

PHP est un langage de scripts libre principalement utilisé pour être exécuté par un serveur http (serveur WEB). Il a été conçu pour permettre la création d’applications WEB dynamiques. PHP peut être installé sur les principaux serveurs web du marché, les plus répandus étant IIS et Apache. PHP est un langage peu typé et souple et donc facile à apprendre par un débutant. PHP est un langage procédural disposant en version 5 de fonctionnalités de modèle objet complètes. C’est pourquoi il faut différencier la version 4 de la version 5 ; Ces 2 serveurs ne peuvent pas cohabiter sur la même machine (du moins très difficilement et avec de grosses contraintes) ; Au jour, où nous rédigeons ces pages, nous avons choisi dans notre étude de cas, d’installer PHP5 pour profiter du maximum d’application du moment.

Nous allons passer à l’installation de PHP5, module indispensable pour permettre l’utilisation de sites WEB dynamiques et allons inclure l’interaction avec la base de données MySQL.

Compiler PHP

• Procédons à la compilation de PHP5

# cd /usr/ports/lang/php5
# make

• L’écran suivant apparaît et permet de choisir les directives de compilation :

Figure 10-1. Compilation PHP

PHP

Voici la liste des directives à cocher avec un « X » :

[X] CLI Build CLI version
[X] CGI Build CGI version
[X] APACHE Build Apache module
[ ] DEBUG Enable debug
[X] SUHOSIN Enable Suhosin protection system (not for jails)
[ ] MULTIBYTE Enable zend multibyte support
[X] IPV6 Enable ipv6 support
[ ] MAILHEAD Enable mail header patch
[ ] REDIRECT Enable force-cgi-redirect support (CGI only)
[ ] DISCARD Enable discard-path support (CGI only)
[X] FASTCGI Enable fastcgi support (CGI only)
[X] PATHINFO Enable path-info-check support (CGI only)

Remarque - vous pouvez compléter en fonction de vos besoins… ne cocher rien de plus sans savoir si vous en avez besoin.

• Il suffit de lancer make pour effectuer la compilation…

# make
# make install

• Créer le fichier du fichier de paramétrage php.ini dans le répertoire /etc avec le fichier d’exemple.

# cd /usr/local/etc 
# cp ./php.ini-dist ./php.ini

• Créer un lien symbolique pour disposer du fichier de paramétrage php.ini dans le répertoire /etc.

# ln -s /usr/local/etc/php.ini /etc/php.ini

Remarque - nous verrons la personnalisation du fichier de configuration après la compilation des extensions PHP.

Compiler les extensions PHP

• Sélectionner les directives et compiler les extensions PHP5 :

# cd /usr/ports/lang/php5-extensions
# make

• L’écran suivant apparaît pour sélectionner les directives de compilation…

Figure 10-2. Compilation extensions PHP

extensions PHP

Voici la liste des directives à cocher avec un « X » :

[X] BCMATH bc style precision math functions
[X] BZ2 bzip2 library support
[ ] CALENDAR calendar conversion support
[X] CTYPE ctype functions
[X] CURL CURL support
[ ] DBA dba support
[ ] DBASE dBase library support
[X] DOM DOM support
[ ] EXIF EXIF support
[ ] FILEINFO fileinfo support
[X] FILTER input filter support
[ ] FRIBIDI FriBidi support
[X] FTP FTP support
[X] GD GD library support
[X] GETTEXT gettext library support
[ ] GMP GNU MP support
[X] HASH HASH Message Digest Framework
[X] ICONV iconv support
[ ] IMAP IMAP support
[ ] INTERBASE Interbase 6 database support (Firebird)
[X] JSON JavaScript Object Serialization support
[ ] LDAP OpenLDAP support
[X] MBSTRING multibyte string support
[X] MCRYPT Encryption support
[ ] MHASH Crypto-hashing support
[ ] MING ming shockwave flash support
[ ] MSSQL MS-SQL database support
[X] MYSQL MySQL database support
[ ] MYSQLI MySQLi database support
[X] NCURSES ncurses support (CLI only)
[ ] ODBC unixODBC support
[ ] OPENSSL OpenSSL support
[ ] PCNTL pcntl support (CLI only)
[X] PCRE Perl Compatible Regular Expression support
[ ] PDF PDFlib support (implies GD)
[X] PDO PHP Data Objects Interface (PDO)
[X] PDO_SQLITE PDO sqlite driver
[ ] PGSQL PostgreSQL database support
[X] POSIX POSIX-like functions
[ ] PSPELL pspell support
[X] READLINE readline support (CLI only)
[X] RECODE recode support
[X] SESSION session support
[ ] SHMOP shmop support
[X] SIMPLEXML simplexml support
[ ] SNMP SNMP support
[ ] SOAP SOAP support
[ ] SOCKETS sockets support
[X] SPL Standard PHP Library
[X] SQLITE sqlite support
[ ] SYBASE_CT Sybase database support
[ ] SYSVMSG System V message support
[ ] SYSVSEM System V semaphore support
[ ] SYSVSHM System V shared memory support
[ ] TIDY TIDY support
[X] TOKENIZER tokenizer support
[ ] WDDX WDDX support (implies XML)│
[X] XML XML support
[X] XMLREADER XMLReader support
[ ] XMLRPC XMLRPC-EPI support
[X] XMLWRITER XMLWriter support
[X] XSL XSL support (Implies DOM)
[ ] YAZ YAZ support (ANSI/NISO Z39.50)
[ ] ZIP ZIP support
[X] ZLIB ZLIB support

Remarque - vous pouvez compléter en fonction de vos besoins… ne cocher rien de plus sans savoir si vous en avez besoin.

• Procédons à l’installation ; vous remarquerez que nous faisons un nettoyage du make et de ses dépendances dans le cas où nous aurions une autre compilation à faire (mais ce n’est pas obligatoire).

# make install
# make clean
# make clean-depends

Personnaliser PHP avec php.ini

Il est très utile de régler PHP et ses comportements ; un fichier de configuration existe et permet de régler de très importants paramétres : Sessions, variables globales, reporting d’erreur, … ; ce fichier est php.ini dans /etc (lien symbolique) ou /usr/local/etc (fichier physique).

• Voici un exemple de configuration :

...
   ;allow_call_time_pass_reference = On
   allow_call_time_pass_reference = Off
...
   ; Examples:
   ;
   ; - Show all errors, except for notices and coding standards warnings
   ;
   ;error_reporting = E_ALL & ~E_NOTICE
   ;
   ; - Show all errors, except for notices
   ;
   ;error_reporting = E_ALL & ~E_NOTICE | E_STRICT
   ;
   ; - Show only errors
   ;
   error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR
   ;
   ; - Show all errors, except coding standards warnings
   ;
   ;error_reporting = E_ALL
... 
  ;post_max_size = 8M
   post_max_size = 20M
...
   ; Magic quotes for incoming GET/POST/Cookie data.
   magic_quotes_gpc = On
...
   ; Maximum allowed size for uploaded files.
   upload_max_filesize = 20M
...

Application PHPMYADMIN

Nous allons passer à l’installation de PHPmyADMIN. Cet outil permet de gérer et superviser la base de données MySQL à partir d’un portail WEB sécurisé

Compilation de PHPMYADMIN

• Procédons à la compilation du module PHPMYADMIN …

# cd /usr/ports/databases/phpmyadmin
# make config

• L’écran suivant apparaît pour sélectionner les directives de compilation…

Figure 11-1. Compilation PHPMYADMIN

PHPmyADMIN

Voici la liste des directives à cocher avec un « X » :

[X] BZ2 bzip2 library support
[X] GD GD library support
[X] MYSQLI Improved MySQL support
[X] OPENSSL OpenSSL support
[ ] PDF PDFlib support (implies GD)
[X] ZLIB ZLIB support
[X] MCRYPT MCrypt library support
[X] MBSTRING Multi-byte character-set string support

Remarque - vous pouvez compléter en fonction de vos besoins… ne cocher rien de plus sans savoir si vous en avez besoin.

• Procédons à la compilation et l’installation.

# make
# make install
# make clean
# make clean-depends

• Laissez le site PHPMYADMIN dans le répertoire d’accueil standard.

# cd /usr/local/www/phpMyAdmin
# chown –R www /usr/local/www/phpMyAdmin
# chmod –R 775 /usr/local/www/phpMyAdmin

• Préparer et configurer le fichier de paramétrage de PHPMYADMIN config.inc.php.

# cd /usr/local/www/phpMyAdmin
# mv config.inc.php config.inc.php.BLANK
# cp config.sample.inc.php config.inc.php
# ln -s /usr/local/www/phpMyAdmin/config.inc.php /usr/local/etc/config.inc.php

• Pour exemple, renseignez le fichier config.inc.php dans /usr/local/etc comme suit :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
* This is needed for cookie based authentication to encrypt password in
* cookie
*/
$cfg['blowfish_secret'] = 'xxxxxxxxx'; /* YOU MUST FILL IN THIS FOR COOKIE AUTH! */
/*
* Servers configuration
*/
$i = 0;
/*
* First server
*/
$i++;
/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'cookie';
/* Server parameters */
$cfg['Servers'][$i]['host'] = 'eserverx330-0';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['compress'] = false;
/* Select mysqli if your server has it */
$cfg['Servers'][$i]['extension'] = 'mysql';
/* User for advanced features */
// $cfg['Servers'][$i]['controluser'] = 'pma';
// $cfg['Servers'][$i]['controlpass'] = 'pmapass';
/* Advanced phpMyAdmin features */
// $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
// $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
// $cfg['Servers'][$i]['relation'] = 'pma_relation';
// $cfg['Servers'][$i]['table_info'] = 'pma_table_info';
// $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
// $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
// $cfg['Servers'][$i]['column_info'] = 'pma_column_info';
// $cfg['Servers'][$i]['history'] = 'pma_history';
// $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';

Configuration d’APACHE

Une fois APACHE et PHP installés, il est nécessaire de configurer APACHE pour accueillir les sites WEB.

Le fichier principal de configuration

• Une fois APACHE et PHP installés, il est nécessaire de configurer APACHE pour accueillir les sites WEB. Editez le fichier httpd.conf dans /usr/local/etc/apache22 :

# vi /usr/local/etc/apache22/httpd.conf

• Vous devez avoir les directives suivantes à jour et nous y incluons tout de suite la partie PHP. Voici un exemple type de fichier de configuration APACHE (le fichier n’est pas complet seuls les extraits importants sont précisés):

# Configuration and logfile names: If the filenames you specify for many
# of the server's control files begin with "/" (or "drive:/" for Win32), the
# server will use that explicit path.  If the filenames do *not* begin
# with "/", the value of ServerRoot is prepended -- so "/var/log/foo.log"
# with ServerRoot set to "/usr/local" will be interpreted by the
# server as "/usr/local//var/log/foo.log".
 
#
# Tuning Environment
#
 
PidFile /var/run/httpd.pid
Timeout 300
KeepAlive On
MaxKeepAliveRequests 0
KeepAliveTimeout 15
MinSpareServers 16
MaxSpareServers 64
StartServers 16
MaxClients 256
MaxRequestsPerChild 100000
HostnameLookups Off
 
#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# Do not add a slash at the end of the directory path.  If you point
# ServerRoot at a non-local disk, be sure to point the LockFile directive
# at a local disk.  If you wish to share the same ServerRoot for multiple
# httpd daemons, you will need to change at least LockFile and PidFile.
#
ServerRoot "/usr/local"
 
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
…
#
# Listen: Allows you to bind Apache to specific IP addresses and/or
# ports, instead of the default. See also the <VirtualHost>
# directive.
#
# Change this to Listen on specific IP addresses as shown below to
# prevent Apache from glomming onto all bound IP addresses.
#
#Listen 12.34.56.78:80
#Listen 80
 
Listen 0.0.0.0:80
 
#
# Dynamic Shared Object (DSO) Support
 
#
# ServerAdmin: Your address, where problems with the server should be
# e-mailed.  This address appears on some server-generated pages, such
# as error documents.  e.g. admin@your-domain.com
#
 
ServerAdmin prenom.nom@domaine.com
 
#
# ServerName gives the name and port that the server uses to identify itself.
# This can often be determined automatically, but we recommend you specify
# it explicitly to prevent problems during startup.
#
# If your host doesn't have a registered DNS name, enter its IP address here.
#
#ServerName www.example.com:80
 
#
# DocumentRoot: The directory out of which you will serve your
# documents. By default, all requests are taken from this directory, but
# symbolic links and aliases may be used to point to other locations.
#
#DocumentRoot "/usr/local/www/apache22/data"
 
DocumentRoot "/var/www"
 
#
#
# This should be changed to whatever you set DocumentRoot to.
#
#<Directory "/usr/local/www/apache22/data">
 
<Directory "/var/www">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
…
#
# DirectoryIndex: sets the file that Apache will serve if a directory
# is requested.
#
#<IfModule dir_module>
#    DirectoryIndex index.html
#</IfModule>
 
<IfModule dir_module>
    <IfModule php5_module>
        DirectoryIndex index.php index.html
    </IfModule>
    <IfModule !php5_module>
        <IfModule php4_module>
            DirectoryIndex index.php index.html
        </IfModule>
        <IfModule !php4_module>
            DirectoryIndex index.html
        </IfModule>
    </IfModule>
</IfModule>
 
#
# The following lines prevent .htaccess and .htpasswd files from being
 
# ErrorLog: The location of the error log file.
# If you do not specify an ErrorLog directive within a <VirtualHost>
# container, error messages relating to that virtual host will be
# logged here.  If you *do* define an error logfile for a <VirtualHost>
# container, that host's errors will be logged there and not here.
#
#ErrorLog /var/log/httpd-error.log
#ErrorLog "|/usr/local/sbin/rotatelogs /var/log/httpd/httpd-error.log 5M"
 
ErrorLog /var/log/httpd-error.log
 
#
# LogLevel: Control the number of messages logged to the error_log.
# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
#
LogLevel warn
<IfModule log_config_module>
    #
    # The following directives define some format nicknames for use with
    # a CustomLog directive (see below).
    #
 
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%h %l %u %t \"%r\" %>s %b" common
 
    #LogFormat "%{Referer}i -> %U" referer
    #LogFormat "%{User-agent}i" agent
 
    <IfModule logio_module>
    # You need to enable mod_logio.c to use %I and %O
    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>
…
    #
    # The location and format of the access logfile (Common Logfile Format).
    # If you do not define any access logfiles within a <VirtualHost>
    # container, they will be logged here.  Contrariwise, if you *do*
    # define per-<VirtualHost> access logfiles, transactions will be
    # logged therein and *not* in this file.
    #
    #CustomLog /var/log/httpd-access.log common
 
    #
    # If you prefer a logfile with access, agent, and referer information
    # (Combined Logfile Format) you can use the following directive.
    #
    #CustomLog /var/log/httpd-access.log combined
 
    CustomLog /var/log/httpd/httpd-access.log combined
</IfModule>…
 
#
# DefaultType: the default MIME type the server will use for a document
# if it cannot otherwise determine one, such as from filename extensions.
# If your server contains mostly text or HTML documents, "text/plain" is
# a good value.  If most of your content is binary, such as applications
# or images, you may want to use "application/octet-stream" instead to
# keep browsers from trying to display binary files as though they are
# text.
#
DefaultType text/plain
<IfModule mime_module><IfModule php4_module>
AddType application/x-httpd-php .php
</IfModule><IfModule php5_module>AddType application/x-httpd-php .php
</IfModule></IfModule>
    #
    # Filters allow you to process content before it is sent to the client.
    #
    # To parse .shtml files for server-side includes (SSI):
    # (You will also need to add "Includes" to the "Options" directive.)
    #
    #AddType text/html .shtml
    #AddOutputFilter INCLUDES .shtml
 
    AddType text/html .htmz
    AddHandler send-gunzipped .htmz
 
#
#EnableMMAP off
#EnableSendfile off
# Server-Status
<Location /server-status>
SetHandler server-status
Order Deny,Allow
Deny from all
Allow from all</Location>
 
# Supplemental configuration
…
 
# Virtual hosts
Include etc/apache22/extra/httpd-vhosts.conf
 
# Alias hosts
Include etc/apache22/extra/httpd-alias.conf
 
# Local access to the Apache HTTP Server Manual
#Include etc/apache22/extra/httpd-manual.conf
…

Les fichiers annexes de configuration

Il existe deux fichiers importants pour paramétrer l’hébergement des sites WEB ; les fichiers httpd-vhosts.conf et httpd-alias.conf ; l’un pour le site principal et l’autre pour les alias.

• Préparez et renseignez le fichier httpd-vhosts.conf dans le répertoire extra :

# cp /usr/local/etc/apache22/extra/httpd-vhosts.conf
/usr/local/etc/apache22/extra/httpd-vhosts.conf.ORIGINAL
# vi /usr/local/etc/apache22/extra/httpd-vhosts.conf
# vi /usr/local/etc/apache22/extra/httpd-alias.conf

• Le fichier httpd-vhosts.conf pourra être renseigné au fur et à mesure des besoins :

#
# Use name-based virtual hosting.
#
 
NameVirtualHost *:80
 
#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ServerName or ServerAlias in any <VirtualHost> block.
#
# <VirtualHost *:80>
#    ServerAdmin webmaster@dummy-host.example.com
#    DocumentRoot "/www/docs/dummy-host.example.com"
#    ServerName dummy-host.example.com
#    ServerAlias www.dummy-host.example.com
#    ErrorLog "/var/log/dummy-host.example.com-error_log"
#    CustomLog "/var/log/dummy-host.example.com-access_log common"
#</VirtualHost>
#
#<VirtualHost *:80>
#    ServerAdmin webmaster@dummy-host2.example.com
#    DocumentRoot "/www/docs/dummy-host2.example.com"
#    ServerName dummy-host2.example.com
#    ErrorLog "/var/log/dummy-host2.example.com-error_log"
#    CustomLog "/var/log/dummy-host2.example.com-access_log common"
#</VirtualHost>
#
 
<VirtualHost *:80>
DocumentRoot /var/www/wwwroot
ServerAdmin prenom.nom@domaine.com
ServerName eserverx330-0
CustomLog "/var/log/httpd/httpd-access.log" combined</VirtualHost>

• Préparez et renseignez le fichier httpd-alias.conf dans le répertoire extra :

#
# Alias
# Alias "/phpinfo&quot; &quot;/var/www/phpinfo"
 <Directory "/var/www/phpinfo">
   Options Indexes FollowSymLinks Includes
   AllowOverride none
   Order allow,deny
   Allow from all
 </Directory>

Remarque - veillez à appliquer la directive AllowOverride none pour éviter de chercher des fichiers .htaccess dans l’arborescence du site car ceci ralentit les accès.

Contrôler le status du serveur APACHE

On peut controler le status du serveur APACHE via une page web ou en ligne de commande ; pour disposer de cette fonction, nous devons installer LYNX (le navigateur web en ligne de commande) et avoir inséré dans le fichier httpd.conf la directive <Location /server-status> (cf.chapitre précédent).

• Procédons à l’installation de LYNX.

# cd /usr/ports/www/lynx
# make
# make install

Remarque - APACHE doit être installé bien évidemment.

• Une fois l’installation de LYNX effectuée, nous pouvons le tester simplement avec la commande apachectl status :

# apachectl status

L’écran suivant apparaît…

                       Apache Server Status for localhost
 
   Server Version: Apache/2.2.6 (FreeBSD) mod_ssl/2.2.6 OpenSSL/0.9.8e
          DAV/2 PHP/5.2.5 with Suhosin-Patch
 
   Server Built: Oct 30 2008 18:55:56
     __________________________________________________________________
 
   Current Time: Wednesday, 26-Nov-2008 22:24:09 CET
   Restart Time: Wednesday, 26-Nov-2008 21:58:05 CET
   Parent Server Generation: 0
   Server uptime: 26 minutes 4 seconds
   1 requests currently being processed, 8 idle workers
 
______W__.......................................................
................................................................
................................................................
................................................................
 
   Scoreboard Key:
   "_" Waiting for Connection, "S" Starting up, "R" Reading Request,
   "W" Sending Reply, "K" Keepalive (read), "D" DNS Lookup,
   "C" Closing connection, "L" Logging, "G" Gracefully finishing,
   "I" Idle cleanup of worker, "." Open slot with no current process

Cette meme page peut être visualisée sur un navigateur Internet avec l’URL ci-après ; des arguments peuvent être passés pour une réactualisation automatique de la page. Voici un exemple :

http://nomduserveur/server-status?refresh=3

?refresh=N ; N correspond au nombre de secondes avant rafraichissement de la page.

Gestionnaire de cache PHP5

« Alternative PHP Cache » (APC) est un cache opcode libre et ouvert pour PHP. Il a été conçu afin de fournir un framework libre, ouvert et robuste pour la mise en cache et l’optimisation de code intermédiaire PHP. Il s’installe automatiquement après compilation ; il suffit de redémarrer APACHE pour la prise en compte.

• Compilez et installez APC pour accèlérer les sites WEB en PHP :

# cd /usr/ports/www/pecl-APC
# make
# make install

• Redémarrez le serveur APACHE pour la prise en charge ; l’extension apc.so doit être installée dans le fichier extension.ini d’APACHE.

# apachectl stop
# apachectl start
 
 

Consultez les chapitres pour parcourir ce dossier.

Aucun commentaire pour “Installer son propre serveur web (part.4)”

Les commentaires sont fermés.

Archives

Visiteurs

Publicité

Warts Republic utilise les réseaux sociaux pour partager ses articles. Warts Republic est enregistré chez Blogasty 09, Flickr, Splush, You Tube, G1 Blog, Facebook, Diggons, Paperblog. Warts Republic bloque les SPAMS avec Askimet. Warts Republic vous recommande les navigateurs de dernière génération tels Firefox, Safari ou IExplorer 7 pour un affichage optimisé.

Tous droits réservés aux auteurs. Consultez la rubrique des droits légaux. Pour toute réclamation, contactez le webmaster, Pour tout autre contact professionel, adressez-vous directement à l'auteur.