July 29, 2017

Setting up Nginx, PHP, and Laravel

We'll start off by installing Nginx, PHP, Composer and getting a Laravel application up and running.

We'll start off by installing Nginx, PHP, Composer and getting a Laravel application up and running.

First, we'll get repositories for the latest software:

sudo add-apt-repository -y ppa:nginx/development
sudo add-apt-repository -y ppa:ondrej/php
sudo apt-get update

Then we'll install the needed software:

# Basics
sudo apt-get install -y git tmux vim curl wget zip unzip htop

# Nginx
sudo apt-get install -y nginx

# PHP
sudo apt-get install -y php7.1-fpm php7.1-cli php7.1-mcrypt php7.1-gd php7.1-mysql \
       php7.1-pgsql php7.1-imap php-memcached php7.1-mbstring php7.1-xml php7.1-curl \
       php7.1-bcmath php7.1-sqlite3 php7.1-xdebug

# Composer
php -r "readfile('http://getcomposer.org/installer');" | sudo php -- --install-dir=/usr/bin/ --filename=composer

After we have PHP and Composer installed, we'll work on getting a Laravel application up and running:

cd /var/www
sudo composer create-project laravel/laravel:dev-develop myapp

Then configure Nginx by editing file /etc/nginx/sites-available/default:

server {
    listen 80 default_server;

    root /var/www/myapp/public;

    index index.html index.htm index.php;

    server_name _;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

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

Note that Nginx is running as www-data and /var/run/php/php7.1-fpm.sock is owned by user/group www-data, so Nginx can read/write to that socket file.

When we try to see our Laravel application in the browser, we'll see we have a permission issues. We can solve this by seeing what user PHP is running as and match the storage and bootstrap directory to that user.

# Check what user PHP-FPM is running as (it's www-data)
ps aux | grep php

# Change owner of storage and bootstrap laravel directories
cd /var/www/myapp
sudo chown -R www-data: storage bootstrap

All Topics