How to enable PHP in nginx?

by scotty_walker , in category: PHP General , 2 years ago

How to enable PHP in nginx?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by rollin , 2 years ago

@scotty_walker 

To enable PHP in nginx, you will need to install and configure PHP-FPM (FastCGI Process Manager) and then modify your nginx configuration to use it. Here are the steps:

  1. Install PHP-FPM on your server:
  • On Ubuntu:
1
2
sudo apt-get update
sudo apt-get install php-fpm


  • On CentOS:
1
2
sudo yum update
sudo yum install php-fpm


  1. Modify the nginx configuration file to use PHP-FPM:


Add the following lines to the server block in your nginx configuration file (usually located at /etc/nginx/nginx.conf):

1
2
3
4
location ~ .php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
}


Make sure to replace php7.4-fpm.sock with the correct socket file for your version of PHP.

  1. Restart nginx to apply the changes:
1
sudo service nginx restart


That's it! PHP should now be enabled in nginx. You can test it by creating a PHP file (e.g. info.php) in your web root (usually /var/www/html) with the following contents:

1
2
3
<?php
phpinfo();
?>


Then, access the file in your web browser (e.g. http://example.com/info.php). If PHP is working correctly, you should see a page with information about your PHP installation.

by dalton_moen , a year ago

@scotty_walker 

To enable PHP in Nginx, you will need to follow these steps:

  1. Install PHP-FPM: sudo apt update sudo apt install php-fpm
  2. Configure PHP-FPM: Open the PHP-FPM configuration file using a text editor: sudo nano /etc/php/7.4/fpm/php.ini Uncomment the following line by removing the semicolon (;) at the beginning: ;cgi.fix_pathinfo=1 Change it to: cgi.fix_pathinfo=0 Save the file and exit the editor.
  3. Configure Nginx to use PHP-FPM: Open the default Nginx configuration file: sudo nano /etc/nginx/sites-available/default Add the following lines within the server block: location ~ .php$ { include snippets/fastcgi-php.conf; # Adjust the socket path to match your PHP-FPM configuration fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; } Save the file and exit the editor.
  4. Restart both Nginx and PHP-FPM to apply the changes: sudo systemctl restart nginx sudo systemctl restart php7.4-fpm


Now PHP should be successfully enabled in Nginx. You can test it by creating a PHP file in the webroot directory (/var/www/html by default) with the following code:

1


Save the file and access it through a web browser by navigating to http://yourdomain.com/yourfile.php. If PHP is working correctly, you should see the PHP information page.