One place for hosting & domains

      Apache

      How To Create a Self-Signed SSL Certificate for Apache in Ubuntu 20.04


      Introduction

      TLS, or “transport layer security” — and its predecessor SSL — are protocols used to wrap normal traffic in a protected, encrypted wrapper. Using this technology, servers can safely send information to their clients without their messages being intercepted or read by an outside party.

      In this guide, we will show you how to create and use a self-signed SSL certificate with the Apache web server on Ubuntu 20.04.

      Note: A self-signed certificate will encrypt communication between your server and any clients. However, because it is not signed by any of the trusted certificate authorities included with web browsers and operating systems, users cannot use the certificate to validate the identity of your server automatically. As a result, your users will see a security error when visiting your site.

      Because of this limitation, self-signed certificates are not appropriate for a production environment serving the public. They are typically used for testing, or for securing non-critical services used by a single user or a small group of users that can establish trust in the certificate’s validity through alternate communication channels.

      For a more production-ready certificate solution, check out Let’s Encrypt, a free certificate authority. You can learn how to download and configure a Let’s Encrypt certificate in our How To Secure Apache with Let’s Encrypt on Ubuntu 20.04 tutorial.

      Prerequisites

      Before starting this tutorial, you’ll need the following:

      • Access to a Ubuntu 20.04 server with a non-root, sudo-enabled user. Our Initial Server Setup with Ubuntu 20.04 guide can show you how to create this account.
      • You will also need to have Apache installed. You can install Apache using apt. First, update the local package index to reflect the latest upstream changes:

      Then, install the apache2 package:

      And finally, if you have a ufw firewall set up, open up the http and https ports:

      • sudo ufw allow "Apache Full"

      After these steps are complete, be sure you are logged in as your non-root user and continue with the tutorial.

      Step 1 — Enabling mod_ssl

      Before we can use any SSL certificates, we first have to enable mod_ssl, an Apache module that provides support for SSL encryption.

      Enable mod_ssl with the a2enmod command:

      Restart Apache to activate the module:

      • sudo systemctl restart apache2

      The mod_ssl module is now enabled and ready for use.

      Step 2 – Creating the SSL Certificate

      Now that Apache is ready to use encryption, we can move on to generating a new SSL certificate. The certificate will store some basic information about your site, and will be accompanied by a key file that allows the server to securely handle encrypted data.

      We can create the SSL key and certificate files with the openssl command:

      • sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/apache-selfsigned.key -out /etc/ssl/certs/apache-selfsigned.crt

      After you enter the command, you will be taken to a prompt where you can enter information about your website. Before we go over that, let’s take a look at what is happening in the command we are issuing:

      • openssl: This is the command line tool for creating and managing OpenSSL certificates, keys, and other files.
      • req -x509: This specifies that we want to use X.509 certificate signing request (CSR) management. X.509 is a public key infrastructure standard that SSL and TLS adhere to for key and certificate management.
      • -nodes: This tells OpenSSL to skip the option to secure our certificate with a passphrase. We need Apache to be able to read the file, without user intervention, when the server starts up. A passphrase would prevent this from happening, since we would have to enter it after every restart.
      • -days 365: This option sets the length of time that the certificate will be considered valid. We set it for one year here. Many modern browsers will reject any certificates that are valid for longer than one year.
      • -newkey rsa:2048: This specifies that we want to generate a new certificate and a new key at the same time. We did not create the key that is required to sign the certificate in a previous step, so we need to create it along with the certificate. The rsa:2048 portion tells it to make an RSA key that is 2048 bits long.
      • -keyout: This line tells OpenSSL where to place the generated private key file that we are creating.
      • -out: This tells OpenSSL where to place the certificate that we are creating.

      Fill out the prompts appropriately. The most important line is the one that requests the Common Name. You need to enter either the hostname you’ll use to access the server by, or the public IP of the server. It’s important that this field matches whatever you’ll put into your browser’s address bar to access the site, as a mismatch will cause more security errors.

      The full list of prompts will look something like this:

      Country Name (2 letter code) [XX]:US
      State or Province Name (full name) []:Example
      Locality Name (eg, city) [Default City]:Example 
      Organization Name (eg, company) [Default Company Ltd]:Example Inc
      Organizational Unit Name (eg, section) []:Example Dept
      Common Name (eg, your name or your server's hostname) []:your_domain_or_ip
      Email Address []:webmaster@example.com
      

      Both of the files you created will be placed in the appropriate subdirectories under /etc/ssl.

      Next we will update our Apache configuration to use the new certificate and key.

      Step 3 – Configuring Apache to Use SSL

      Now that we have our self-signed certificate and key available, we need to update our Apache configuration to use them. On Ubuntu, you can place new Apache configuration files (they must end in .conf) into /etc/apache2/sites-available/and they will be loaded the next time the Apache process is reloaded or restarted.

      For this tutorial we will create a new minimal configuration file. (If you already have an Apache <Virtualhost> set up and just need to add SSL to it, you will likely need to copy over the configuration lines that start with SSL, and switch the VirtualHost port from 80 to 443. We will take care of port 80 in the next step.)

      Open a new file in the /etc/apache2/sites-available directory:

      • sudo nano /etc/apache2/sites-available/your_domain_or_ip.conf

      Paste in the following minimal VirtualHost configuration:

      /etc/apache2/sites-available/your_domain_or_ip.conf

      <VirtualHost *:443>
         ServerName your_domain_or_ip
         DocumentRoot /var/www/your_domain_or_ip
      
         SSLEngine on
         SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt
         SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key
      </VirtualHost>
      
      

      Be sure to update the ServerName line to however you intend to address your server. This can be a hostname, full domain name, or an IP address. Make sure whatever you choose matches the Common Name you chose when making the certificate.

      The remaining lines specify a DocumentRoot directory to serve files from, and the SSL options needed to point Apache to our newly-created certificate and key.

      Now let’s create our DocumentRoot and put an HTML file in it just for testing purposes:

      • sudo mkdir /var/www/your_domain_or_ip

      Open a new index.html file with your text editor:

      • sudo nano /var/www/your_domain_or_ip/index.html

      Paste the following into the blank file:

      /var/www/your_domain_or_ip/index.html

      <h1>it worked!</h1>
      

      This is not a full HTML file, of course, but browsers are lenient and it will be enough to verify our configuration.

      Save and close the file
      Next, we need to enable the configuration file with the a2ensite tool:

      • sudo a2ensite your_domain_or_ip.conf

      Next, let’s test for configuration errors:

      • sudo apache2ctl configtest

      If everything is successful, you will get a result that looks like this:

      Output

      AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message Syntax OK

      The first line is a message telling you that the ServerName directive is not set globally. If you want to get rid of that message, you can set ServerName to your server’s domain name or IP address in /etc/apache2/apache2.conf. This is optional as the message will do no harm.

      If your output has Syntax OK in it, your configuration file has no syntax errors. We can safely reload Apache to implement our changes:

      • sudo systemctl reload apache2

      Now load your site in a browser, being sure to use https:// at the beginning.

      You should see an error. This is normal for a self-signed certificate! The browser is warning you that it can’t verify the identity of the server, because our certificate is not signed by any of its known certificate authorities. For testing purposes and personal use this can be fine. You should be able to click through to advanced or more information and choose to proceed.

      After you do so, your browser will load the it worked! message.

      Note: if your browser doesn’t connect at all to the server, make sure your connection isn’t being blocked by a firewall. If you are using ufw, the following commands will open ports 80 and 443:

      • sudo ufw allow "Apache Full"

      Next we will add another VirtualHost section to our configuration to serve plain HTTP requests and redirect them to HTTPS.

      Step 4 — Redirecting HTTP to HTTPS

      Currently, our configuration will only respond to HTTPS requests on port 443. It is good practice to also respond on port 80, even if you want to force all traffic to be encrypted. Let’s set up a VirtualHost to respond to these unencrypted requests and redirect them to HTTPS.

      Open the same Apache configuration file we started in previous steps:

      • sudo nano /etc/apache2/sites-available/your_domain_or_ip.conf

      At the bottom, create another VirtualHost block to match requests on port 80. Use the ServerName directive to again match your domain name or IP address. Then, use Redirect to match any requests and send them to the SSL VirtualHost. Make sure to include the trailing slash:

      /etc/apache2/sites-available/your_domain_or_ip.conf

      <VirtualHost *:80>
          ServerName your_domain_or_ip
          Redirect / https://your_domain_or_ip/
      </VirtualHost>
      

      Save and close this file when you are finished, then test your configuration syntax again, and reload Apache:

      • sudo apachectl configtest
      • sudo systemctl reload apache2

      You can test the new redirect functionality by visiting your site with plain http:// in front of the address. You should be redirected to https:// automatically.

      Conclusion

      You have now configured Apache to serve encrypted requests using a self-signed SSL certificate, and to redirect unencrypted HTTP requests to HTTPS.

      If you are planning on using SSL for a public website, you should look into purchasing a domain name and using a widely supported certificate authority such as Let’s Encrypt.

      For more information on using Let’s Encrypt with Apache, please read our How To Secure Apache with Let’s Encrypt on Ubuntu 20.04 tutorial.



      Source link

      How To Create a Self-Signed SSL Certificate for Apache on CentOS 8


      Not using CentOS 8?


      Choose a different version or distribution.

      Introduction

      TLS, or “transport layer security” — and its predecessor SSL — are protocols used to wrap normal traffic in a protected, encrypted wrapper. Using this technology, servers can safely send information to their clients without their messages being intercepted or read by an outside party.

      In this guide, we will show you how to create and use a self-signed SSL certificate with the Apache web server on a CentOS 8 machine.

      Note: A self-signed certificate will encrypt communication between your server and its clients. However, because it is not signed by any of the trusted certificate authorities included with web browsers and operating systems, users cannot use the certificate to automatically validate the identity of your server. As a result, your users will see a security error when visiting your site.

      Because of this limitation, self-signed certificates are not appropriate for a production environment serving the public. They are typically used for testing, or for securing non-critical services used by a single user or a small group of users that can establish trust in the certificate’s validity through alternate communication channels.

      For a more production-ready certificate solution, check out Let’s Encrypt, a free certificate authority. You can learn how to download and configure a Let’s Encrypt certificate in our How To Secure Apache with Let’s Encrypt on CentOS 8 tutorial.

      Prerequisites

      Before starting this tutorial, you’ll need the following:

      • Access to a CentOS 8 server with a non-root, sudo-enabled user. Our Initial Server Setup with CentOS 8 guide can show you how to create this account.
      • You will also need to have Apache installed. You can install Apache using dnf:

        Enable Apache and start it using systemctl:

        • sudo systemctl enable httpd
        • sudo systemctl start httpd

        And finally, if you have a firewalld firewall set up, open up the http and https ports:

        • sudo firewall-cmd --permanent --add-service=http
        • sudo firewall-cmd --permanent --add-service=https
        • sudo firewall-cmd --reload

      After these steps are complete, be sure you are logged in as your non-root user and continue with the tutorial.

      Step 1 — Installing mod_ssl

      We first need to install mod_ssl, an Apache module that provides support for SSL encryption.

      Install mod_ssl with the dnf command:

      Because of a packaging bug, we need to restart Apache once to properly generate the default SSL certificate and key, otherwise we’ll get an error reading '/etc/pki/tls/certs/localhost.crt' does not exist or is empty.

      • sudo systemctl restart httpd

      The mod_ssl module is now enabled and ready for use.

      Step 2 — Creating the SSL Certificate

      Now that Apache is ready to use encryption, we can move on to generating a new SSL certificate. The certificate will store some basic information about your site, and will be accompanied by a key file that allows the server to securely handle encrypted data.

      We can create the SSL key and certificate files with the openssl command:

      • sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/pki/tls/private/apache-selfsigned.key -out /etc/pki/tls/certs/apache-selfsigned.crt

      After you enter the command, you will be taken to a prompt where you can enter information about your website. Before we go over that, let’s take a look at what is happening in the command we are issuing:

      • openssl: This is the command line tool for creating and managing OpenSSL certificates, keys, and other files.
      • req -x509: This specifies that we want to use X.509 certificate signing request (CSR) management. X.509 is a public key infrastructure standard that SSL and TLS adhere to for key and certificate management.
      • -nodes: This tells OpenSSL to skip the option to secure our certificate with a passphrase. We need Apache to be able to read the file, without user intervention, when the server starts up. A passphrase would prevent this from happening, since we would have to enter it after every restart.
      • -days 365: This option sets the length of time that the certificate will be considered valid. We set it for one year here. Many modern browsers will reject any certificates that are valid for longer than one year.
      • -newkey rsa:2048: This specifies that we want to generate a new certificate and a new key at the same time. We did not create the key that is required to sign the certificate in a previous step, so we need to create it along with the certificate. The rsa:2048 portion tells it to make an RSA key that is 2048 bits long.
      • -keyout: This line tells OpenSSL where to place the generated private key file that we are creating.
      • -out: This tells OpenSSL where to place the certificate that we are creating.

      Fill out the prompts appropriately. The most important line is the one that requests the Common Name. You need to enter either the hostname you’ll use to access the server by, or the public IP of the server. It’s important that this field matches whatever you’ll put into your browser’s address bar to access the site, as a mismatch will cause more security errors.

      The full list of prompts will look something like this:

      Country Name (2 letter code) [XX]:US
      State or Province Name (full name) []:Example
      Locality Name (eg, city) [Default City]:Example 
      Organization Name (eg, company) [Default Company Ltd]:Example Inc
      Organizational Unit Name (eg, section) []:Example Dept
      Common Name (eg, your name or your server's hostname) []:your_domain_or_ip
      Email Address []:webmaster@example.com
      

      Both of the files you created will be placed in the appropriate subdirectories of the /etc/pki/tls directory. This is a standard directory provided by CentOS for this purpose.

      Next we will update our Apache configuration to use the new certificate and key.

      Step 3 — Configuring Apache to Use SSL

      Now that we have our self-signed certificate and key available, we need to update our Apache configuration to use them. On CentOS, you can place new Apache configuration files (they must end in .conf) into /etc/httpd/conf.d and they will be loaded the next time the Apache process is reloaded or restarted.

      For this tutorial we will create a new minimal configuration file. If you already have an Apache <Virtualhost> set up and just need to add SSL to it, you will likely need to copy over the configuration lines that start with SSL, and switch the VirtualHost port from 80 to 443. We will take care of port 80 in the next step.

      Open a new file in the /etc/httpd/conf.d directory:

      • sudo vi /etc/httpd/conf.d/your_domain_or_ip.conf

      Paste in the following minimal VirtualHost configuration:

      /etc/httpd/conf.d/your_domain_or_ip.conf

      <VirtualHost *:443>
          ServerName your_domain_or_ip
          DocumentRoot /var/www/ssl-test
          SSLEngine on
          SSLCertificateFile /etc/pki/tls/certs/apache-selfsigned.crt
          SSLCertificateKeyFile /etc/pki/tls/private/apache-selfsigned.key
      </VirtualHost>
      

      Be sure to update the ServerName line to however you intend to address your server. This can be a hostname, full domain name, or an IP address. Make sure whatever you choose matches the Common Name you chose when making the certificate.

      The remaining lines specify a DocumentRoot directory to serve files from, and the SSL options needed to point Apache to our newly-created certificate and key.

      Now let’s create our DocumentRoot and put an HTML file in it just for testing purposes:

      • sudo mkdir /var/www/ssl-test

      Open a new index.html file with your text editor:

      • sudo vi /var/www/ssl-test/index.html

      Paste the following into the blank file:

      /var/www/ssl-test/index.html

      <h1>it worked!</h1>
      

      This is not a full HTML file, of course, but browsers are lenient and it will be enough to verify our configuration.

      Save and close the file, then check your Apache configuration for syntax errors by typing:

      • sudo apachectl configtest

      You may see some warnings, but as long as the output ends with Syntax OK, you are safe to continue. If this is not part of your output, check the syntax of your files and try again.

      When all is well, reload Apache to pick up the configuration changes:

      • sudo systemctl reload httpd

      Now load your site in a browser, being sure to use https:// at the beginning.

      You should see an error. This is normal for a self-signed certificate! The browser is warning you that it can’t verify the identity of the server, because our certificate is not signed by any of the browser’s known certificate authorities. For testing purposes and personal use this can be fine. You should be able to click through to advanced or more information and choose to proceed.

      After you do so, your browser will load the it worked! message.

      Note: if your browser doesn’t connect at all to the server, make sure your connection isn’t being blocked by a firewall. If you are using firewalld, the following commands will open ports 80 and 443:

      • sudo firewall-cmd --permanent --add-service=http
      • sudo firewall-cmd --permanent --add-service=https
      • sudo firewall-cmd --reload

      Next we will add another VirtualHost section to our configuration to serve plain HTTP requests and redirect them to HTTPS.

      Step 4 — Redirecting HTTP to HTTPS

      Currently, our configuration will only respond to HTTPS requests on port 443. It is good practice to also respond on port 80, even if you want to force all traffic to be encrypted. Let’s set up a VirtualHost to respond to these unencrypted requests and redirect them to HTTPS.

      Open the same Apache configuration file we started in previous steps:

      • sudo vi /etc/httpd/conf.d/your_domain_or_ip.conf

      At the bottom, create another VirtualHost block to match requests on port 80. Use the ServerName directive to again match your domain name or IP address. Then, use Redirect to match any requests and send them to the SSL VirtualHost. Make sure to include the trailing slash:

      /etc/httpd/conf.d/your_domain_or_ip.conf

      <VirtualHost *:80>
          ServerName your_domain_or_ip
          Redirect / https://your_domain_or_ip/
      </VirtualHost>
      

      Save and close this file when you are finished, then test your configuration syntax again, and reload Apache:

      • sudo apachectl configtest
      • sudo systemctl reload httpd

      You can test the new redirect functionality by visiting your site with plain http:// in front of the address. You should be redirected to https:// automatically.

      Conclusion

      You have now configured Apache to serve encrypted requests using a self-signed SSL certificate, and to redirect unecrypted HTTP requests to HTTPS.

      If you are planning on using SSL for a public website, you should look into purchasing a domain name and using a widely supported certificate authority such as Let’s Encrypt.

      For more information on using Let’s Encrypt with Apache, please read our How To Secure Apache with Let’s Encrypt on CentOS 8 tutorial.



      Source link

      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