How to set up Nginx and PHP-FPM to handle HTTPS and SSL/TLS encryption?

To set up Nginx and PHP-FPM to handle HTTPS and SSL/TLS encryption, you need to perform the following steps:

  1. Install Nginx and PHP-FPM:

    • Install Nginx by running the command: sudo apt-get install nginx
    • Install PHP-FPM by running the command: sudo apt-get install php-fpm
  2. Generate SSL/TLS certificate:

    • Obtain an SSL/TLS certificate either by purchasing one or using a free service like Let's Encrypt.
    • Follow the certificate provider's instructions to generate the necessary certificate files.
  3. Configure Nginx:

    • Open the Nginx configuration file using your preferred text editor, such as sudo nano /etc/nginx/sites-available/default.
    • In the server block, add the following lines before the closing bracket: listen 443 ssl; ssl_certificate /path/to/ssl_certificate.crt; ssl_certificate_key /path/to/ssl_certificate.key; Replace /path/to/ssl_certificate.crt and /path/to/ssl_certificate.key with the paths to your SSL/TLS certificate files.
    • Uncomment the line index.php in the location ~ \.php$ block to enable PHP processing.
  4. Configure PHP-FPM:

    • Open the PHP-FPM configuration file using your preferred text editor, such as sudo nano /etc/php/7.4/fpm/php.ini.
    • Search for ;cgi.fix_pathinfo=1 and change it to cgi.fix_pathinfo=0.
    • Save and close the file.
  5. Restart the services:

    • Restart Nginx by running the command: sudo service nginx restart
    • Restart PHP-FPM by running the command: sudo service php7.4-fpm restart
  6. Test the setup:

    • Create a simple PHP file in the web root directory. For example, create index.php file with the content: <?php phpinfo(); ?>
    • Open your browser and visit https://your_domain to verify that SSL/TLS encryption is working and PHP scripts are being executed correctly.

That's it! You have successfully set up Nginx and PHP-FPM to handle HTTPS and SSL/TLS encryption. Remember to replace your_domain with your actual domain name or server IP address.