Nginx & PHP On WSL2

I had a project that was being worked on that required the code be written in PHP. The code would end up on a Linux machine which resulted me in wanting to code in an environment that was close to what production would be. This would allow to quickly debug and figure out what could go wrong once the code was pushed to production. There are several routes that I could have taken. Install Ubuntu on the host, I could have ran a virtual machine or even setup a server and sync files one way or another.

Windows Subsystem for Linux 2 to the rescue!

WSL2 provided all the features that I wanted. To be able to debug with no internet connection, Lightweight and fast.

Time to install

Launch the bash shell.

PHP Installation

#Install PHP
sudo apt install php7.2 php7.2-cli php7.2-mysql php7.2-fpm
#Check the version
php -version

Nginx Installation

# Install Nginx
sudo apt install nginx

# Start Nginx server
sudo service nginx start

wsl 2 & Networking

Wsl 2 uses a virtual switch to route traffic. We will need to obtain the IP address for the network interface

ip addr show
Image showing results of ip addr show

Visit http://[yourIP] in your favorite browser and you should receive something similar to the below image.

Image showing Nginx's default index.html

Setting up PHP-FPM

The next steps is setting up the PHP-FPM processor. We need to get the unix sock file that the PHP-FPM service will listen on.

grep "listen =" /etc/php/7.2/fpm/pool.d/www.conf
#output: listen = /run/php/php7.2-fpm.sock

#start the service
sudo service php7.2-fpm start

We need to modify the Nginx default server block settings.

sudo nano /etc/nginx/sites-available/default

Add the following location location block to the default site.

location ~ \.php$ {
                 include snippets/fastcgi-php.conf;
 
                 # Make sure unix socket path matches PHP-FPM configured path above
                 fastcgi_pass unix:/run/php/php7.2-fpm.sock;
 
                 # Prevent ERR_INCOMPLETE_CHUNKED_ENCODING when browser hangs on response
                 fastcgi_buffering off;
         } 

We will need to restart the Nginx server for it to load the new settings.

sudo service nginx restart

Lets create a simple php file that shows the php info.

sudo nano /var/www/html/info.php

Input the following.

<php
phpinfo();
?>

Visit http://[YourIP]/info.php.

If everything works you should get the standard PHP info page.

Image showing php info screen.

Next step would be modifying the permissions to allow your regular user account read/write access and setting up an IDE to remote connect to WSL2 such as Visual Studio code and work on your next awesome project!