One place for hosting & domains

      Versions

      How To Run Multiple PHP Versions on One Server Using Apache and PHP-FPM on Ubuntu 20.04


      Not using Ubuntu 20.04?


      Choose a different version or distribution.

      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      The Apache web server uses virtual hosts to manage multiple domains on a single instance. Similarly, PHP-FPM uses a daemon to manage multiple PHP versions on a single instance. Together, you can use Apache and PHP-FPM to host multiple PHP web-applications, each using a different version of PHP, all on the same server, and all at the same time. This is useful because different applications may require different versions of PHP, but some server stacks, like a regularly configured LAMP stack, can only manage one. Combining Apache with PHP-FPM is also a more cost-efficient solution than hosting each application on its own instance.

      PHP-FPM also offers configuration options for stderr and stdout logging, emergency restarts, and adaptive process spawning, which is useful for heavy-loaded sites. In fact, using Apache with PHP-FPM is one of the best stacks for hosting PHP applications, especially when it comes to performance.

      In fact, using Apache with PHP-FPM is one of the best stacks for hosting PHP applications, especially when it comes to performance. PHP-FPM not only allows you run to multiple PHP versions simultaneously, it also provides numerous extra features like adaptive process spawning, which is useful for heavy-loaded sites.

      In this tutorial you will set up two PHP sites on a single instance. Each site will use its own domain, and each domain will deploy its own version of PHP. The first, site1.your_domain, will deploy PHP 7.2. The second, site2.your_domain, will deploy PHP 7.3.

      Prerequisites

      Step 1 — Installing PHP Versions 7.2 and 7.3 with PHP-FPM

      With the prerequisites completed, you will now install PHP versions 7.2 and 7.3, as well as PHP-FPM and several additional extensions. But to accomplish this, you will first need to add the Ondrej PHP repository to your system.

      Execute the apt-get command to install software-properties-common:

      • sudo apt-get install software-properties-common -y

      The software-properties-common package provides apt-add-repository command-line utility which you will use to add the ondrej/php PPA (Personal Package Archive) repository.

      Now add the ondrej/php repository to your system. The ondrej/php PPA will have more up-to-date versions of PHP than the official Ubuntu repositories, and it will also allow you to install multiple versions of PHP in the same system:

      • sudo add-apt-repository ppa:ondrej/php

      Update the repository:

      Next, install php7.2, php7.2-fpm, php7.2-mysql, libapache2-mod-php7.2, and libapache2-mod-fcgid with the following commands:

      • sudo apt-get install php7.2 php7.2-fpm php7.2-mysql libapache2-mod-php7.2 libapache2-mod-fcgid -y
      • php7.2 is a metapackage used to run PHP applications.
      • php7.2-fpm provides the Fast Process Manager interpreter that runs as a daemon and receives Fast/CGI requests.
      • php7.2-mysql connects PHP to the MySQL database.
      • libapache2-mod-php7.2 provides the PHP module for the Apache webserver.
      • libapache2-mod-fcgid contains a mod_fcgid that starts a number of CGI program instances to handle concurrent requests.

      Now repeat the process for PHP version 7.3. Install php7.3, php7.3-fpm, php7.3-mysql, and libapache2-mod-php7.3.

      • sudo apt-get install php7.3 php7.3-fpm php7.3-mysql libapache2-mod-php7.3 -y

      After installing both PHP versions, start the php7.2-fpm service:

      • sudo systemctl start php7.2-fpm

      Next, verify the status of php7.2-fpm service:

      • sudo systemctl status php7.2-fpm

      You’ll see the following output:

      Output

      • ● php7.2-fpm.service - The PHP 7.2 FastCGI Process Manager
      • Loaded: loaded (/lib/systemd/system/php7.2-fpm.service; enabled; vendor preset: enabled)
      • Active: active (running) since Fri 2020-06-05 11:25:07 UTC; 1min 38s ago
      • Docs: man:php-fpm7.2(8)
      • Main PID: 13703 (php-fpm7.2)
      • Status: "Processes active: 0, idle: 2, Requests: 0, slow: 0, Traffic: 0req/sec"
      • Tasks: 3 (limit: 2353)
      • Memory: 6.2M
      • CGroup: /system.slice/php7.2-fpm.service
      • ├─13703 php-fpm: master process (/etc/php/7.2/fpm/php-fpm.conf)
      • ├─13719 php-fpm: pool www
      • └─13720 php-fpm: pool www
      • Jun 05 11:25:07 ubuntu systemd[1]: Starting The PHP 7.2 FastCGI Process Manager...
      • Jun 05 11:25:07 ubuntu systemd[1]: Started The PHP 7.2 FastCGI Process Manager.

      Repeating this process, now start the php7.3-fpm service:

      • sudo systemctl start php7.3-fpm

      Next, verify the status of php7.3-fpm service:

      • sudo systemctl status php7.3-fpm

      You’ll see the following output:

      Output

      • ● php7.3-fpm.service - The PHP 7.3 FastCGI Process Manager
      • Loaded: loaded (/lib/systemd/system/php7.3-fpm.service; enabled; vendor preset: enabled)
      • Active: active (running) since Fri 2020-06-05 11:26:33 UTC; 56s ago
      • Docs: man:php-fpm7.3(8)
      • Process: 23470 ExecStartPost=/usr/lib/php/php-fpm-socket-helper install /run/php/php-fpm.sock /etc/php/7.3/fpm/pool.d/www.conf 73 (code=ex>
      • Main PID: 23452 (php-fpm7.3)
      • Status: "Processes active: 0, idle: 2, Requests: 0, slow: 0, Traffic: 0req/sec"
      • Tasks: 3 (limit: 2353)
      • Memory: 7.1M
      • CGroup: /system.slice/php7.3-fpm.service
      • ├─23452 php-fpm: master process (/etc/php/7.3/fpm/php-fpm.conf)
      • ├─23468 php-fpm: pool www
      • └─23469 php-fpm: pool www
      • Jun 05 11:26:33 ubuntu systemd[1]: Starting The PHP 7.3 FastCGI Process Manager...
      • Jun 05 11:26:33 ubuntu systemd[1]: Started The PHP 7.3 FastCGI Process Manager.

      Lastly, you must enable several modules so that your Apache2 service can work with multiple PHP versions:

      • sudo a2enmod actions fcgid alias proxy_fcgi
      • actions is used for executing CGI scripts based on media type or request method.

      • fcgid is a high performance alternative to mod_cgi that starts a sufficient number of instances of the CGI program to handle concurrent requests.

      • alias provides for the mapping of different parts of the host filesystem in the document tree, and for URL redirection.

      • proxy_fcgi allows Apache to forward requests to PHP-FPM.

      Now restart the Apache service to apply your changes:

      • sudo systemctl restart apache2

      At this point you have installed two PHP versions on your server. Next, you will create a directory structure for each website you want to deploy.

      Step 2 — Creating Directory Structures for Both Websites

      In this section, you will create a document root directory and an index page for each of your two websites.

      First, create document root directories for both site1.your_domain and site2.your_domain:

      • sudo mkdir /var/www/site1.your_domain
      • sudo mkdir /var/www/site2.your_domain

      By default, the Apache webserver runs as a www-data user and www-data group. To ensure that you have the correct ownership and permissions of your website root directories, execute the following commands:

      • sudo chown -R www-data:www-data /var/www/site1.your_domain
      • sudo chown -R www-data:www-data /var/www/site2.your_domain
      • sudo chmod -R 755 /var/www/site1.your_domain
      • sudo chmod -R 755 /var/www/site2.your_domain

      Next you will create an info.php file inside each website root directory. This will display each website’s PHP version information. Begin with site1:

      • sudo nano /var/www/site1.your_domain/info.php

      Add the following line:

      /var/www/site1.your_domain/info.php

      <?php phpinfo(); ?>
      

      Save and close the file. Now copy the info.php file you created to site2:

      • sudo cp /var/www/site1.your_domain/info.php /var/www/site2.your_domain/info.php

      Your web server should now have the document root directories that each site requires to serve data to visitors. Next, you will configure your Apache web server to work with two different PHP versions.

      Step 3 — Configuring Apache for Both Websites

      In this section, you will create two virtual host configuration files. This will enable your two websites to work simultaneously with two different PHP versions.

      In order for Apache to serve this content, it is necessary to create a virtual host file with the correct directives. Instead of modifying the default configuration file located at /etc/apache2/sites-available/000-default.conf, you’ll create two new ones inside the directory /etc/apache2/sites-available/.

      First create a new virtual host configuration file for the website site1.your_domain. Here you will direct Apache to render content using php7.2:

      • sudo nano /etc/apache2/sites-available/site1.your_domain.conf

      Add the following content. Make sure the website directory path, server name, and PHP version match your setup:

      /etc/apache2/sites-available/site1.your_domain.conf

      
      <VirtualHost *:80>
           ServerAdmin admin@site1.your_domain
           ServerName site1.your_domain
           DocumentRoot /var/www/site1.your_domain
           DirectoryIndex info.php
      
           <Directory /var/www/site1.your_domain>
              Options Indexes FollowSymLinks MultiViews
              AllowOverride All
              Order allow,deny
              allow from all
           </Directory>
      
          <FilesMatch .php$>
              # From the Apache version 2.4.10 and above, use the SetHandler to run PHP as a fastCGI process server
               SetHandler "proxy:unix:/run/php/php7.2-fpm.sock|fcgi://localhost"
          </FilesMatch>
      
           ErrorLog ${APACHE_LOG_DIR}/site1.your_domain_error.log
           CustomLog ${APACHE_LOG_DIR}/site1.your_domain_access.log combined
      </VirtualHost>
      

      In this file you updated the DocumentRoot to your new directory and ServerAdmin to an email that the your_domain site administrator can access. You’ve also updated ServerName, which establishes the base domain for this virtual host configuration, and you’ve added a SetHandler directive to run PHP as a fastCGI process server.

      Save and close the file.

      Next, create a new virtual host configuration file for the website site2.your_domain. You will specify this subdomain to deploy php7.3:

      • sudo nano /etc/apache2/sites-available/site2.your_domain.conf

      Add the following content. Again, make sure the website directory path, server name, and PHP version match your unique information:

      /etc/apache2/sites-available/site2.your_domain.conf

      <VirtualHost *:80>
           ServerAdmin admin@site2.your_domain
           ServerName site2.your_domain
           DocumentRoot /var/www/site2.your_domain
           DirectoryIndex info.php
      
           <Directory /var/www/site2.your_domain>
              Options Indexes FollowSymLinks MultiViews
              AllowOverride All
              Order allow,deny
              allow from all
           </Directory>
      
          <FilesMatch .php$>
              # 2.4.10+ can proxy to unix socket
               SetHandler "proxy:unix:/run/php/php7.3-fpm.sock|fcgi://localhost"
          </FilesMatch>
      
           ErrorLog ${APACHE_LOG_DIR}/site2.your_domain_error.log
           CustomLog ${APACHE_LOG_DIR}/site2.your_domain_access.log combined
      </VirtualHost>
      

      Save and close the file when you are finished. Then, check the Apache configuration file for any syntax errors:

      • sudo apachectl configtest

      You’ll see the following output:

      Output

      Next, enable both virtual host configuration files with the following commands:

      • sudo a2ensite site1.your_domain
      • sudo a2ensite site2.your_domain

      Now disable the default site, since you won’t need it.:

      • sudo a2dissite 000-default.conf

      Finally, restart the Apache service to implement your changes:

      • sudo systemctl restart apache2

      Now that you have configured Apache to serve each site, you will test them to make sure the proper PHP versions are running.

      Step 4 — Testing Both Websites

      At this point, you have configured two websites to run two different versions of PHP. Now test the results.

      Open your web browser and visit both sites http://site1.your_domain and http://site2.your_domain. You will see two pages that look like this:

      PHP 7.2 info page
      PHP 7.3 info page

      Note the titles. The first page indicates that site1.your_domain deployed PHP version 7.2. The second indicates that site2.your_domain deployed PHP version 7.3.

      Now that you’ve tested your sites, remove the info.php files. Because they contain sensitive information about your server and are accessible to unauthorized users, they pose a security vulnerability. To remove both files, run the following commands:

      • sudo rm -rf /var/www/site1.your_domain/info.php
      • sudo rm -rf /var/www/site2.your_domain/info.php

      You now have a single Ubuntu 20.04 server handling two websites with two different PHP versions. PHP-FPM, however, is not limited to this one application.

      Conclusion

      You have now combined virtual hosts and PHP-FPM to serve multiple websites and multiple versions of PHP on a single server. The only practical limit on the number of PHP sites and PHP versions that your Apache service can handle is the processing power of your instance.

      From here you might consider exploring PHP-FPM’s more advanced features, like its adaptive spawning process or how it can log sdtout and stderr Alternatively, you could now secure your websites. To accomplish this, you can follow our tutorial on how to secure your sites with free TLS/SSL certificates from Let’s Encrypt.



      Source link

      How To Run Multiple PHP Versions on One Server Using Apache and PHP-FPM on CentOS 8


      Not using CentOS 8?


      Choose a different version or distribution.

      The author selected the COVID-19 Relief Fund to receive a donation as part of the Write for DOnations program.

      Introduction

      The Apache web server uses virtual hosts to manage multiple domains on a single instance. Similarly, PHP-FPM uses a daemon to manage multiple PHP versions on a single instance. Together, you can use Apache and PHP-FPM to host multiple PHP web-applications, each using a different version of PHP, all on the same server, and all at the same time. This is useful because different applications may require different versions of PHP, but some server stacks, like a regularly configured LAMP stack, can only manage one. Combining Apache with PHP-FPM is also a more cost-efficient solution than hosting each application on its own instance.

      PHP-FPM also offers configuration options for stderr and stdout logging, emergency restarts, and adaptive process spawning, which is useful for heavy-loaded sites. In fact, using Apache with PHP-FPM is one of the best stacks for hosting PHP applications, especially when it comes to performance.

      In this tutorial you will set up two PHP sites on a single instance. Each site will use its own domain, and each domain will deploy its own version of PHP. The first, site1.your_domain, will deploy PHP 7.3. The second, site2.your_domain, will deploy PHP 7.4.

      Prerequisites

      Step 1 — Installing PHP Versions 7.3 and 7.4 with PHP-FPM

      With the prerequisites completed, you will now install PHP versions 7.3 and 7.4, as well as PHP-FPM and several additional extensions. In order to install multiple versions of PHP, you will need to install and enable the Remi repository to your system. Which also offers the latest versions of the PHP stack on CentOS 8 system.

      You can add the both repository to your system using the below commands:

      • sudo dnf install http://rpms.remirepo.net/enterprise/remi-release-8.rpm

      The command above will also enable the EPEL repository.

      First let’s discover what versions of PHP 7 are available on Remi:

      You’ll see an output like this:

      Output

      Remi's Modular repository for Enterprise Linux 8 - x86_64 Name Stream Profiles Summary php remi-7.2 common [d], devel, minimal PHP scripting language php remi-7.3 common [d], devel, minimal PHP scripting language php remi-7.4 common [d], devel, minimal PHP scripting language

      Next, disable the default PHP module and enable Remi’s PHP7.3 module using the below command:

      • sudo dnf module reset php
      • sudo dnf module enable php:remi-7.3

      Lets start to installing php73 and php73-php-fpm:

      • sudo dnf install php73 php73-php-fpm -y
      • php73 is a metapackage that can be used to run PHP application.
      • php73-php-fpm provides the Fast Process Manager interpreter that runs as a daemon and receives Fast/CGI requests.

      Now repeat the process for PHP version 7.4. Install php74 and php74-php-fpm.

      • sudo dnf module reset php
      • sudo dnf module enable php:remi-7.4
      • sudo dnf install php74 php74-php-fpm -y

      After installing both PHP versions, start the php73-php-fpm service and enable it to start at boot with the following commands:

      • sudo systemctl start php73-php-fpm
      • sudo systemctl enable php73-php-fpm

      Next, verify the status of php73-php-fpm service with the following commands:

      • sudo systemctl status php73-php-fpm

      You’ll see the following output:

      • ● php73-php-fpm.service - The PHP FastCGI Process Manager
      • Loaded: loaded (/usr/lib/systemd/system/php73-php-fpm.service; enabled; vendor preset: disabled)
      • Active: active (running) since Wed 2020-04-22 05:14:46 UTC; 52s ago
      • Main PID: 14206 (php-fpm)
      • Status: "Processes active: 0, idle: 5, Requests: 0, slow: 0, Traffic: 0req/sec"
      • Tasks: 6 (limit: 5059)
      • Memory: 25.9M
      • CGroup: /system.slice/php73-php-fpm.service
      • ├─14206 php-fpm: master process (/etc/opt/remi/php73/php-fpm.conf)
      • ├─14207 php-fpm: pool www
      • ├─14208 php-fpm: pool www
      • ├─14209 php-fpm: pool www
      • ├─14210 php-fpm: pool www
      • └─14211 php-fpm: pool www
      • Apr 22 05:14:46 centos-s-1vcpu-1gb-nyc3-01 systemd[1]: Starting The PHP FastCGI Process Manager...
      • Apr 22 05:14:46 centos-s-1vcpu-1gb-nyc3-01 systemd[1]: Started The PHP FastCGI Process Manager.

      Repeating this process, now start the php74-php-fpm service and enable it to start at boot with the following commands:

      • sudo systemctl start php74-php-fpm
      • sudo systemctl enable php74-php-fpm

      And then verify the status of php74-php-fpm service with the following commands:

      • sudo systemctl status php74-php-fpm

      You’ll see the following output:

      • ● php74-php-fpm.service - The PHP FastCGI Process Manager
      • Loaded: loaded (/usr/lib/systemd/system/php74-php-fpm.service; enabled; vendor preset: disabled)
      • Active: active (running) since Wed 2020-04-22 05:16:16 UTC; 23s ago
      • Main PID: 14244 (php-fpm)
      • Status: "Processes active: 0, idle: 5, Requests: 0, slow: 0, Traffic: 0req/sec"
      • Tasks: 6 (limit: 5059)
      • Memory: 18.8M
      • CGroup: /system.slice/php74-php-fpm.service
      • ├─14244 php-fpm: master process (/etc/opt/remi/php74/php-fpm.conf)
      • ├─14245 php-fpm: pool www
      • ├─14246 php-fpm: pool www
      • ├─14247 php-fpm: pool www
      • ├─14248 php-fpm: pool www
      • └─14249 php-fpm: pool www
      • Apr 22 05:16:15 centos-s-1vcpu-1gb-nyc3-01 systemd[1]: Starting The PHP FastCGI Process Manager...
      • Apr 22 05:16:16 centos-s-1vcpu-1gb-nyc3-01 systemd[1]: Started The PHP FastCGI Process Manager.

      At this point you have installed two PHP versions on your server. Next, you will create a directory structure for each website you want to deploy.

      Step 2 — Creating Directory Structures for Both Websites

      In this section, you will create a document root directory and an index page for each of your two websites.

      First, create document root directories for both site1.yourdomain and site2.yourdomain:

      • sudo mkdir /var/www/site1.your_domain
      • sudo mkdir /var/www/site2.your_domain

      By default, Apache webserver runs as a apache user and apache group. To ensure that you have the correct ownership and permissions of your website root directories, execute the following commands:

      • sudo chown -R apache:apache /var/www/site1.your_domain
      • sudo chown -R apache:apache /var/www/site2.your_domain
      • sudo chmod -R 755 /var/www/site1.your_domain
      • sudo chmod -R 755 /var/www/site2.your_domain

      The chown command changes the ownership of your two website directories to the apache user and the apache group. The chmod command changes the permissions associated with that user and group, as well as others.

      Next you will create an info.php file inside each website root directory. This will display each website’s PHP version information. Begin with site1:

      • sudo vi /var/www/site1.your_domain/info.php

      Add the following line:

      site1.your_domain/info.php’>/var/www/site1.your_domain/info.php

      <?php phpinfo(); ?>
      

      Save and close the file. Now copy the info.php file you created to site2:

      • sudo cp /var/www/site1.your_domain/info.php /var/www/site2.your_domain/info.php

      Your web server now has the document root directories that each site requires to serve data to visitors. Next, you will configure your Apache web server to work with two different PHP versions.

      Step 3 — Configuring Apache for Both Websites

      In this section, you will create two virtual host configuration files. This will enable your two websites to work simultaneously with two different PHP versions.

      In order for Apache to serve this content, it is necessary to create a virtual host file with the correct directives. You’ll create two new virtual host configuration file inside the directory /etc/httpd/conf.d/.

      First create a new virtual host configuration file for the website site1.your_domain. Here you will direct Apache to render content using php7.3:

      • sudo vi /etc/httpd/conf.d/site1.your_domain.conf

      Add the following content. Make sure the website directory path, server name, and PHP version match your setup:

      /etc/httpd/conf.d/site1.your_domain.conf

      <VirtualHost *:80>
           ServerAdmin admin@site1.your_domain
           ServerName site1.your_domain
           DocumentRoot /var/www/site1.your_domain
           DirectoryIndex info.php
           ErrorLog /var/log/httpd/site1.your_domain-error.log
           CustomLog /var/log/httpd/site1.your_domain-access.log combined
      
        <IfModule !mod_php7.c>
          <FilesMatch .(php|phar)$>
              SetHandler "proxy:unix:/var/opt/remi/php73/run/php-fpm/www.sock|fcgi://localhost"
          </FilesMatch>
        </IfModule>
      
      </VirtualHost>
      

      For DocumentRoot you are specifying the path of your website root directory. For ServerAdmin you are adding an email that the your_domain site administrator can access. For ServerName you are adding the url for your first subdomain. For SetHandler you are specifying the PHP-FPM socket file for php7.3.

      Save and close the file.

      Next, create a new virtual host configuration file for the website site2.your_domain. You will specify this subdomain to deploy php7.4:

      • sudo vi /etc/httpd/conf.d/site2.your_domain.conf

      Add the following content. Again, make sure the website directory path, server name, and PHP version match your unique information:

      /etc/httpd/conf.d/site2.your_domain.conf

      <VirtualHost *:80>
           ServerAdmin admin@site2.your_domain
           ServerName site2.your_domain
           DocumentRoot /var/www/site2.your_domain
           DirectoryIndex info.php
           ErrorLog /var/log/httpd/site2.your_domain-error.log
           CustomLog /var/log/httpd/site2.your_domain-access.log combined
        <IfModule !mod_php7.c>
          <FilesMatch .(php|phar)$>
              SetHandler "proxy:unix:/var/opt/remi/php74/run/php-fpm/www.sock|fcgi://localhost"
          </FilesMatch>
        </IfModule>
      
      </VirtualHost>
      

      Save and close the file when you are finished. Then, check the Apache configuration file for any syntax errors with the following command:

      • sudo apachectl configtest

      You’ll see an output printing Syntax OK:

      Output

      Finally, restart the Apache service to implement your changes:

      • sudo systemctl restart httpd

      Now that you have configured Apache to serve each site, you will test them to make sure the proper PHP versions are running.

      Step 4 — Testing Both Websites

      At this point, you have configured two websites to run two different versions of PHP. Now test the results.

      Open your web browser and visit both sites http://site1.your_domain and http://site2.your_domain. You will see two pages that look like this:

      PHP 7.3 info page
      PHP 7.4 info page

      Note the titles. The first page indicates that site1.yourdomain deployed PHP version 7.3. The second indicates that site2.yourdomain deployed PHP version 7.4.

      Now that you’ve tested your sites, remove the info.php files. Because they contain sensitive information about your server and are accessible to unauthorized users, they pose a security vulnerability. To remove both files, run the following commands:

      • sudo rm -rf /var/www/site1.your_domain/info.php
      • sudo rm -rf /var/www/site2.your_domain/info.php

      You now have a single CentOS 8 server handling two websites with two different PHP versions. PHP-FPM, however, is not limited to this one application.

      Conclusion

      You have now combined virtual hosts and PHP-FPM to serve multiple websites and multiple versions of PHP on a single server. The only practical limit on the number of PHP sites and PHP versions that your Apache service can handle is the processing power of your instance.

      From here you might consider exploring PHP-FPM’s more advanced features, like its adaptive spawning process or how it can log sdtout and stderr. Alternatively, you could now secure your websites with free TLS/SSL certificates from Let’s Encrypt.



      Source link

      Comment exécuter plusieurs Versions PHP sur un serveur en utilisant Apache et PHP-FPM sur CentOS 7


      L’auteur a choisi le COVID-19 Relief Fund pour recevoir un don dans le cadre du programme Write for DOnations.

      Introduction

      Le serveur web Apache utilise des hôtes virtuels pour gérer plusieurs domaines sur une seule instance. De même, PHP-FPM utilise un démon pour gérer plusieurs versions PHP sur une seule instance. Vous pouvez utiliser ensemble Apache et PHP-FPM pour héberger plusieurs applications Web PHP, chacune utilisant une version différente de PHP, toutes sur le même serveur, et toutes en même temps. C’est utile car différentes applications peuvent nécessiter différentes versions de PHP, mais certaines piles de serveurs, telles qu’une pile LAMP régulièrement configurée, ne peuvent gérer qu’une seule version. Combiner Apache avec PHP-FPM est également une solution plus économique que d’héberger chaque application sur sa propre instance.

      PHP-FPM offre également des options de configuration pour la journalisation stderr et stdout, les redémarrages d’urgence et le lancement de processus adaptatifs, ce qui est utile pour les sites très chargés. En fait, l’utilisation d’Apache avec PHP-FPM est l’une des meilleures piles pour héberger des applications PHP, surtout en matière de performances.

      Dans ce tutoriel, vous allez configurer deux sites PHP sur une seule instance. Chaque site utilisera son propre domaine, et chaque domaine déploiera sa propre version de PHP. Le premier, site1.your_domain, déploiera PHP 7.0. La deuxième, site2.your_domain, déploiera PHP 7.2.

      Conditions préalables

      Étape 1 – Installation des Versions PHP 7.0 et 7.2 avec PHP-FPM

      Une fois les conditions préalables remplies, vous allez maintenant installer les versions PHP 7.0 et 7.2. Le référentiel SCL (Collections de logiciels) maintient de nombreuses versions de la pile PHP pour le système CentOS 7. Si vous avez besoin de la version la plus récente de PHP et qu’elle n’est pas disponible sur SCL, consultez plutôt le PPA (personal package archive) de remi.

      Commencez par installer le référentiel SCL sur votre système :

      • sudo yum install centos-release-scl -y

      Voyons d’abord quelles versions de PHP 7 sont disponibles sur SCL :

      • sudo yum list rh-php7[0-9].x86_64

      Vous verrez une sortie de ce type :

      Output

      Available Packages rh-php70.x86_64 2.3-1.el7 centos-sclo-rh rh-php71.x86_64 1-1.el7 centos-sclo-rh rh-php72.x86_64 1-2.el7 centos-sclo-rh rh-php73.x86_64 1-1.el7 centos-sclo-rh

      Vous verrez que la version la plus récente, PHP 7.3, est également disponible. Pour nos exemples, nous allons toutefois installer les versions 7.0 et 7.2.

      Commençons par la version la plus ancienne. Installez rh-php70 et rh-php70-php-fpm :

      • sudo yum install rh-php70 rh-php70-php-fpm -y
      • rh-php70 est un metapackage qui exécute des applications PHP.
      • rh-php70-php-fpm fournit l’interpréteur Fast Process Manager qui fonctionne comme démon et reçoit des requêtes Fast/CGI.

      Repérez maintenant le processus pour la version PHP 7.2. Installez rh-php72 et rh-php72-php-fpm.

      • sudo yum install rh-php72 rh-php72-php-fpm -y

      Ensuite, exécutez les commandes suivantes pour commencer à utiliser les deux collections logicielles :

      • sudo scl enable rh-php70 bash
      • sudo scl enable rh-php72 bash

      Par défaut, les deux versions de PHP sont à l’écoute sur le port 9000. Mais dans ce tutoriel, nous voulons exécuter deux versions simultanément. Par conséquent, nous allons désigner deux nouveaux ports :

      Pour ce faire, vous pouvez ouvrir /etc/opt/rh/rh-php70/php-fpm.d/www.conf dans votre éditeur de texte préféré et changer chaque apparence de 9000 à 9002. Ensuite, enregistrez et fermez le fichier et répétez le processus pour /etc/opt/rh/rh-php72/php-fpm.d/www.conf, ne remplacez maintenant 9000 que par 9003. Vous pouvez en outre utiliser ces deux commandes sed pour faire les remplaçants :

      • sudo sed -i 's/:9000/:9002/' /etc/opt/rh/rh-php70/php-fpm.d/www.conf
      • sudo sed -i 's/:9000/:9003/' /etc/opt/rh/rh-php72/php-fpm.d/www.conf

      Vous avez maintenant désigné un port dédié pour chacun de vos services PHP. Cependant, avant que ces modifications ne fonctionnent, vous devez ajouter les ports à votre configuration SELinux.

      CentOS 7. Vous devez ajouter vos nouveaux ports 9002 et 9003 à votre base de données SELinux et les attribuer à vos services httpd, sinon vos applications ne fonctionneront pas. Utilisez la commande semanage pour effectuer cette tâche :

      • sudo semanage port -a -t http_port_t -p tcp 9002
      • sudo semanage port -a -t http_port_t -p tcp 9003

      Le drapeau -a spécifie que vous ajoutez un objet à la base de données. Le drapeau -t spécifie le type d’objet, qui dans ce cas est http_port_t​​​. Et le drapeau -p désigne le protocole tcp. Vous pouvez en apprendre davantage sur SELinux et la commande semanage dans ce tutoriel, ou en consultant la documentation officielle SELinux.

      Maintenant, vous êtes prêt à démarrer et à activer vos services PHP. Commencez par votre service rh-php70-php-fpm et activez-le au démarrage :

      • sudo systemctl start rh-php70-php-fpm
      • sudo systemctl enable rh-php70-php-fpm

      Ensuite, vérifiez l’état de votre service rh-php70-php-fpm

      • sudo systemctl status rh-php70-php-fpm

      Vous verrez une sortie de ce type :

      Output

      ● rh-php70-php-fpm.service - The PHP FastCGI Process Manager Loaded: loaded (/usr/lib/systemd/system/rh-php70-php-fpm.service; enabled; vendor preset: disabled) Active: active (running) since Sat 2020-04-18 04:49:59 UTC; 1min 6s ago Main PID: 1852 (php-fpm) Status: "Processes active: 0, idle: 5, Requests: 0, slow: 0, Traffic: 0req/sec" CGroup: /system.slice/rh-php70-php-fpm.service ├─1852 php-fpm: master process (/etc/opt/rh/rh-php70/php-fpm.conf) ├─1853 php-fpm: pool www ├─1854 php-fpm: pool www ├─1855 php-fpm: pool www ├─1856 php-fpm: pool www └─1857 php-fpm: pool www Apr 18 04:49:59 centos-s-1vcpu-1gb-blr1-01 systemd[1]: Starting The PHP FastCGI Process Manager... Apr 18 04:49:59 centos-s-1vcpu-1gb-blr1-01 systemd[1]: Started The PHP FastCGI Process Manager.

      En répétant ce processus, démarrez le service rh-php72-php-fpm et activez-le au démarrage :

      • sudo systemctl start rh-php72-php-fpm
      • sudo systemctl enable rh-php72-php-fpm

      Ensuite, vérifiez l’état de votre service rh-php72-php-fpm

      • sudo systemctl status rh-php72-php-fpm

      Vous verrez une autre sortie comme celle-ci :

      Output

      ● rh-php72-php-fpm.service - The PHP FastCGI Process Manager Loaded: loaded (/usr/lib/systemd/system/rh-php72-php-fpm.service; enabled; vendor preset: disabled) Active: active (running) since Sat 2020-04-18 04:50:04 UTC; 1min 59s ago Main PID: 1876 (php-fpm) Status: "Processes active: 0, idle: 5, Requests: 0, slow: 0, Traffic: 0req/sec" CGroup: /system.slice/rh-php72-php-fpm.service ├─1876 php-fpm: master process (/etc/opt/rh/rh-php72/php-fpm.conf) ├─1877 php-fpm: pool www ├─1878 php-fpm: pool www ├─1879 php-fpm: pool www ├─1880 php-fpm: pool www └─1881 php-fpm: pool www Apr 18 04:50:04 centos-s-1vcpu-1gb-blr1-01 systemd[1]: Starting The PHP FastCGI Process Manager... Apr 18 04:50:04 centos-s-1vcpu-1gb-blr1-01 systemd[1]: Started The PHP FastCGI Process Manager.

      À ce stade, vous avez installé deux versions PHP sur votre serveur. Ensuite, vous allez créer une structure de répertoire pour chaque site web que vous voulez déployer.

      Étape 2 — Création de structures répertoire pour les deux sites Web

      Dans cette section, vous créerez un répertoire root de document et une page index pour chacun de vos deux sites Web.

      Tout d’abord, créez des répertoires root de documents à la fois pour site1.your_domain et site2.your_domain

      • sudo mkdir /var/www/site1.your_domain
      • sudo mkdir /var/www/site2.your_domain

      Par défaut, le serveur web Apache fonctionne comme un utilisateur apache et un groupe apache. Donc /var/www/ et tous ses fichiers et sous-répertoires devraient également leur appartenir. Exécutez les commandes suivantes pour vérifier la propriété et les autorisations correctes des répertoires racines de votre site web :

      • sudo chown -R apache:apache /var/www/site1.your_domain
      • sudo chown -R apache:apache /var/www/site2.your_domain
      • sudo chmod -R 755 /var/www/site1.your_domain
      • sudo chmod -R 755 /var/www/site2.your_domain

      La commande chown change la propriété des deux répertoires de votre site web pour l’utilisateur apache et le groupe apache. La commande chmod modifie les permissions associées à cet utilisateur et au groupe, ainsi qu’à d’autres.

      Ensuite, vous allez créer un fichier info.php à l’intérieur du répertoire root de chaque site Web. Cela affichera les informations de version PHP de chaque site Web. Commencez avec site1

      • sudo vi /var/www/site1.your_domain/info.php

      Ajoutez la ligne suivante :

      /var/www/site1.your_domain/info.php

      <?php phpinfo(); ?>
      

      Enregistrez et fermez le fichier. Copiez maintenant le fichier info.php que vous avez créé sur site2

      • sudo cp /var/www/site1.your_domain/info.php /var/www/site2.your_domain/info.php

      Votre serveur web dispose maintenant des répertoires racine des documents dont chaque site a besoin pour fournir des données aux visiteurs. Ensuite, vous allez configurer votre serveur web Apache pour qu’il fonctionne avec deux versions PHP différentes.

      Étape 3 — Configuration d’Apache pour les deux sites Web

      Dans cette section, vous allez créer deux fichiers de configuration d’hôte virtuel. Cela permettra à vos deux sites web de fonctionner simultanément avec deux versions PHP différentes.

      Pour qu’Apache puisse servir ce contenu, il est nécessaire de créer un fichier d’hôte virtuel avec les directives correctes. Vous allez créer deux nouveaux fichiers de configuration d’hôte virtuel dans le répertoire /etc/httpd/conf.d/.

      Commencez par créer un nouveau fichier de configuration d’hôte virtuel pour le site Web site1.your_domain. Ici, vous allez indiquer à Apache de rendre le contenu en utilisant PHP 7.0 :

      • sudo vi /etc/httpd/conf.d/site1.your_domain.conf

      Ajoutez le contenu suivant. Assurez-vous le chemin du répertoire du site Web, le nom du serveur, le port et la version PHP correspondent à votre configuration :

      /etc/httpd/conf.d/site1.your_domain.conf

      
      <VirtualHost *:80>
           ServerAdmin admin@site1.your_domain
           ServerName site1.your_domain
           DocumentRoot /var/www/site1.your_domain
           DirectoryIndex info.php
           SetHandler "proxy:fcgi://127.0.0.1:9002
           ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
           AddHandler php70-fcgi .php
           Action php70-fcgi /cgi-bin/php70.fcgi
           ErrorLog /var/log/httpd/site1.your_domain_error.log
           CustomLog /var/log/httpd/site1.your_domain_access.log combined
      </VirtualHost>
      

      Pour DocumentRoot, vous spécifiez le chemin du répertoire racine de votre site web. Pour ServerAdmin, vous ajoutez un courriel auquel l’administrateur du site your_domain peut accéder. Pour ServerName, vous ajoutez l’url de votre premier sous-domaine. Pour SetHandler, vous spécifiez le port 9002. Les autres directives configurent également votre service pour déployer PHP 7.0.

      Enregistrez et fermez le fichier.

      Ensuite, créez un nouveau fichier de configuration d’hôte virtuel pour le site Web site2.your_domain. Vous allez spécifier ce sous domaine pour déployer PHP 7.2 :

      • sudo vi /etc/httpd/conf.d/site2.your_domain.conf

      Ajoutez le contenu suivant. Là encore, assurez-vous que le chemin d’accès au répertoire du site web, le nom du serveur, le port et la version PHP correspondent à vos informations uniques :

      /etc/httpd/conf.d/site2.your_domain.conf

      <VirtualHost *:80>
           ServerAdmin admin@site2.your_domain
           ServerName site2.your_domain
           DocumentRoot /var/www/site2.your_domain
           DirectoryIndex info.php
           SetHandler "proxy:fcgi://127.0.0.1:9003
           ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
           AddHandler php72-fcgi .php
           Action php72-fcgi /cgi-bin/php72.fcgi
           ErrorLog /var/log/httpd/site2.your_domain_error.log
           CustomLog /var/log/httpd/site2.your_domain_access.log combined
      </VirtualHost>
      

      Enregistrez et fermez le fichier lorsque vous avez terminé. Vérifiez ensuite le fichier de configuration Apache pour détecter toute erreur de syntaxe :

      • sudo apachectl configtest

      Vous verrez une sortie d’impression Syntax OK :

      Output

      Enfin, redémarrez le service Apache pour implémenter vos changements :

      • sudo systemctl restart httpd

      Maintenant que vous avez configuré Apache pour servir chaque site, vous allez tester les sites pour vous assurer que les versions PHP adéquates tournent.

      Étape 4 — Test des deux sites Web

      À ce stade, vous avez configuré deux sites web pour exécuter deux versions différentes de PHP. Testez maintenant les résultats.

      Ouvrez votre navigateur web et consultez les deux sites http://site1.your_domain et http://site2.your_domain Vous verrez deux pages qui ressemblent à ceci :

      PHP 7.0 info pagePHP 7.2 info page

      Notez les titres. La première page indique que site1.your_domain a déployé PHP version 7.0. La deuxième indique que site2.your_domain a déployé PHP version 7.2.

      Maintenant que vous avez testé vos sites, supprimez les fichiers info.php. Étant donné qu’ils contiennent des informations sensibles sur votre serveur et sont accessibles a des utilisateurs non autorisés, ils constituent une faille de sécurité. Supprimez les fichiers :

      • sudo rm -rf /var/www/site1.your_domain/info.php
      • sudo rm -rf /var/www/site2.your_domain/info.php

      Vous disposez désormais d’un seul serveur CentOS 7 qui gère deux sites web avec deux versions différentes de PHP. Cela dit, PHP-FPM n’est pas limité à cette seule application.

      Conclusion

      Vous avez maintenant combiné des hôtes virtuels et PHP-FPM pour servir plusieurs sites web et plusieurs versions de PHP sur un seul serveur. La seule limite pratique sur le nombre de sites PHP et les versions PHP que votre service Apache peut gérer est la puissance de traitement de votre instance.

      À partir de là, vous pourriez envisager d’explorer les fonctionnalités plus avancées de PHP-FPM, comme son processus de spawning adaptatif ou la façon dont il peut enregistrer sdtout et stderr.  Par ailleurs, vous pourriez désormais sécuriser vos sites web. Pour ce faire, vous pouvez suivre notre tutoriel sur comment sécuriser vos sites avec des certificats TLS/SSL gratuits de Let’s Encrypt.



      Source link