How to Deploy Laravel Application with Nginx on Ubuntu - TechvBlogs

How to Deploy Laravel Application with Nginx on Ubuntu

Laravel is the most popular PHP framework to build web applications fast. Follow this blog to deploy your Laravel application with Nginx on Ubuntu.


Smit Pipaliya - Author - TechvBlogs
Smit Pipaliya
 

2 years ago

TechvBlogs - Google News

Laravel is one of the most popular open-source web application frameworks written in PHP. It aims to help developers build complex and straightforward applications by making frequently used application tasks (like caching and authentication) easier.

This blog will deploy a simple Laravel application with a production environment in mind, which requires a few common steps. For example, applications should use a dedicated database user with access limited to necessary databases. File permissions should guarantee that only required directories and files are writable. Application settings should be taken into consideration to make sure no debugging information is being displayed to the end-user, which could expose application configuration details.

This blog will show you how to install Laravel with Nginx on Ubuntu.

1. Prerequisites

  • The operating system running Ubuntu Linux
  • A root or non-root user with Sudo privileges
  • Has stable internet connection
  • Terminal window / Command line

2. Install Nginx On Ubuntu

If you have installed Nginx, you can skip this step. If you have not installed Nginx, then you click on this link: Install Nginx on Ubuntu 20.04 LTS

3. Install PHP On Ubuntu

Laravel is based on PHP, so you’ll need to install PHP and related modules. PHP 8 is the default in Ubuntu repositories at the time of this writing.

To install PHP and related modules, run the following commands:

#! /bin/bash
sudo apt-get update
sudo apt-get install software-properties-common -y
sudo add-apt-repository ppa:ondrej/php -y
sudo apt-get install php8.0 php8.0-mbstring php8.0-gettext php8.0-zip php8.0-fpm php8.0-curl php8.0-mysql php8.0-gd php8.0-cgi php8.0-soap php8.0-sqlite3 php8.0-xml php8.0-redis php8.0-bcmath php8.0-imagick php8.0-intl -y

The -y flag in the command will automatically allow the server to install PHP 8. If you don’t add the -y flag, it will simply ask you for confirmation.

PHP 8 should be installed and ready to use.

3. Install Composer On Ubuntu

There are a few steps that we can follow to deploy Laravel on Nginx. The first one is to install all the required dependencies on the server. The second is to clone the git repository or create a new Laravel project inside our project directory.
So, Let's get started with the first step.

If we are going to clone a git repo, we have to install git on our server. It is straightforward. And, we also have to install composer on the server because we have to install Laravel's dependencies using composer update or composer install command. So, Let's, first of all, install the git and composer on our server.

Execute the following commands to install git and composer on the Ubuntu server.

#! /bin/bash
sudo apt-get install git composer -y

Read Also: What's New in Laravel 9: New Features of Laravel 9

4. Install Laravel

Option 1: Clone a Git Repository

Git is a free and open-source distributed version control system designed to handle small and extensive projects with speed and efficiency. You are probably using git as a version control system for your Laravel project. We now have git installed on our server. We can clone a git repository.

In this demonstration, I will clone the official Laravel git repository. But you can clone your project repository from Github, Bitbucket, or any other service provider. First, we have to clear our project directory. Otherwise, git will not clone the application code.

Run the following command to clear the project directory.

#! /bin/bash
cd /var/www/html
sudo rm -rf * .*

In my case, the project directory is /var/www/html because the document root is /var/www/html/public. So, I have to clear everything inside my project directory. Yours can be different. You can find the project directory from your Nginx virtual host.
Once the project directory is clean, execute the git clone command to clone your repository. I am cloning the official Laravel git repository from Github.com in this demonstration.

#! /bin/bash
cd /var/www/html
sudo git clone https://github.com/laravel/laravel.git .
sudo composer install

For example, I am cloning the Laravel project from the official git repository of Laravel. You can clone your project from the repository you desire. Just replace the URL, and you are good to go. We added the "." at the end of the git clone command to clone the project files in the same directory.

Option 2: Deploy a new Laravel Project

Similar to option 1, we first have to clear our project directory. We have to remove all the files inside our project directory by clear. You can follow that step from Option 1.

Once done, run the following command in your project directory to create a brand new Laravel Project.

#! /bin/bash
cd /var/www/html
sudo composer create-project --prefer-dist laravel/laravel .

5. Update Permission

We have to give ownership to www-data so that Nginx can create cache and update Laravel log files. Execute the following command to change file permissions.

#! /bin/bash
sudo chown -R www-data:www-data /var/www/html

Now, you will be able to access your website by accessing your domain name or IP address of the server. Now, Let’s see how to create a brand new Laravel project on the server.

6. Update ENV File and Generate An Encryption Key

To copy the file from .env.example to .env and generate an encryption key, run the following commands.

#! /bin/bash
cd /var/www/html
sudo cp .env.example .env
php artisan key:generate

Next, edit the .env file and define your database:

#! /bin/bash
cd /var/www/html
sudo nano .env

Change the following lines:

APP_URL=https://techvblogs.com

DB_CONNECTION=mysql
DB_HOST=YOUR_DB_HOST
DB_PORT=3306
DB_DATABASE=techvblogs
DB_USERNAME=admin
DB_PASSWORD=YOUR_PASSWORD

 After updating your .env file, press CTRL+XY, and Enter key to save the .env file.

7. Configure Nginx for Laravel

Laravel is tricky. It is because the main index.php file of the project lives in the project's public directory. It means that we have to update our virtual host so that it should route the traffic into the public directory inside our project directory.

Next, We will need to create an Nginx virtual host configuration file for Laravel. Run the following command:

#! /bin/bash
sudo nano /etc/nginx/sites-available/techvblogs.conf

 Add the following lines:

server {
    listen 80;
    server_name techvblogs.com;
    root /var/www/html/public;

    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";

    index index.php;

    charset utf-8;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location = /favicon.ico { access_log off; log_not_found off; }
    location = /robots.txt  { access_log off; log_not_found off; }

    error_page 404 /index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php8.0-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
    }

    location ~ /\.(?!well-known).* {
        deny all;
    }
}

After updating your virtual host file, press CTRL+XY, and Enter key to save the updated virtual host file.

Next, configure the Laravel virtual host above, enable it. Run the following command:

#! /bin/bash
sudo ln -s /etc/nginx/sites-available/techvblogs.conf /etc/nginx/sites-enabled/techvblogs.conf

Finally, restart the Nginx server to apply the changes. Run the following command:

#! /bin/bash
sudo systemctl restart nginx

 If your Nginx server successfully restarts, you will be able to access your Laravel project in the browser.

Thank you for reading this blog.

Read Also: How to Deploy Laravel Project with Apache on Ubuntu

If you want to manage your VPS / VM Server without touching the command line go and  Checkout this linkServerAvatar allows you to quickly set up WordPress or Custom PHP websites on VPS / VM in a  matter of minutes.  You can host multiple websites on a single VPS / VM, configure SSL certificates, and monitor the health of your server without ever touching the command line interface.

If you have any queries or doubts about this topic please feel free to contact us. We will try to reach you.

Comments (3)

Birk Birk 1 year ago

it doesn't work, I get 403 nginx error

TechvBlogs TechvBlogs 1 year ago

Permission issue right?

sudo chown -R www-data:www-data /var/www/html

Please check your directory permission.

Hassam Hassam 1 year ago

Thank you for your solution. I have an error on how to fix index.php because it is in public folder. now it fixed. as we simply add /public for root e.g root /home/domain1/public_html/public;. I shared my Nginx config file. hope it is helpful for other developers. Replace domain1 with your domain name.

server {
    server_name domain1.com www.domain1.com;
    listen 143.190.21X.1XX;
    root /home/domain1/public_html/public;
    index index.php index.htm index.html;
    access_log /var/log/virtualmin/domain1.com_access_log;
    error_log /var/log/virtualmin/domain1.com_error_log;
    fastcgi_param GATEWAY_INTERFACE CGI/1.1;
    fastcgi_param SERVER_SOFTWARE nginx;
    fastcgi_param QUERY_STRING $query_string;
    fastcgi_param REQUEST_METHOD $request_method;
    fastcgi_param CONTENT_TYPE $content_type;
    fastcgi_param CONTENT_LENGTH $content_length;
    fastcgi_param SCRIPT_FILENAME "/home/domain1/public_html$fastcgi_script_name";
    fastcgi_param SCRIPT_NAME $fastcgi_script_name;
    fastcgi_param REQUEST_URI $request_uri;
    fastcgi_param DOCUMENT_URI $document_uri;
    fastcgi_param DOCUMENT_ROOT /home/domain1/public_html;
    fastcgi_param SERVER_PROTOCOL $server_protocol;
    fastcgi_param REMOTE_ADDR $remote_addr;
    fastcgi_param REMOTE_PORT $remote_port;
    fastcgi_param SERVER_ADDR $server_addr;
    fastcgi_param SERVER_PORT $server_port;
    fastcgi_param SERVER_NAME $server_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;
    fastcgi_param HTTPS $https;
    add_header X-Frame-Options "SAMEORIGIN";
    add_header X-Content-Type-Options "nosniff";
    gzip on;
    gzip_disable "msie6";
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_min_length 256;
    gzip_types
      application/geo+json
      application/javascript
      application/x-javascript
      application/json
      application/ld+json
      application/manifest+json
      application/rdf+xml
      application/rss+xml
      application/xhtml+xml
      application/xml
      font/eot
      font/otf
      font/ttf
      image/svg+xml
      text/css
      text/javascript
      text/plain
      text/xml;
    client_max_body_size 48M;
    # fixed permalink_issues
    location / {
        try_files $uri $uri/ /index.php?$args;
    }
    location ^~ /.well-known/ {
        try_files $uri /;
    }
    location ~ "\.php(/|$)" {
        try_files $uri $fastcgi_script_name =404;
        default_type application/x-httpd-php;
        fastcgi_pass unix:/var/php-nginx/1671702822117723.sock/socket;
		#hassam
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
		#hassam
    }
    fastcgi_split_path_info "^(.+\.php)(/.+)$";
    location /cgi-bin/ {
        gzip off;
        root /home/domain1/cgi-bin;
        fastcgi_pass unix:/var/fcgiwrap/1671702822117723.sock/socket;
        fastcgi_param SCRIPT_FILENAME "/home/domain1$fastcgi_script_name";
        fastcgi_param GATEWAY_INTERFACE CGI/1.1;
        fastcgi_param SERVER_SOFTWARE nginx;
        fastcgi_param QUERY_STRING $query_string;
        fastcgi_param REQUEST_METHOD $request_method;
        fastcgi_param CONTENT_TYPE $content_type;
        fastcgi_param CONTENT_LENGTH $content_length;
        fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        fastcgi_param REQUEST_URI $request_uri;
        fastcgi_param DOCUMENT_URI $document_uri;
        fastcgi_param DOCUMENT_ROOT /home/domain1/public_html;
        fastcgi_param SERVER_PROTOCOL $server_protocol;
        fastcgi_param REMOTE_ADDR $remote_addr;
        fastcgi_param REMOTE_PORT $remote_port;
        fastcgi_param SERVER_ADDR $server_addr;
        fastcgi_param SERVER_PORT $server_port;
        fastcgi_param SERVER_NAME $server_name;
        fastcgi_param PATH_INFO $fastcgi_path_info;
        fastcgi_param HTTPS $https;
    }
    fastcgi_read_timeout 60;
    # START Nginx Rewrites for Sitemaps
    rewrite ^/sitemap_index.xml$ /index.php?sitemap=1 last;
    rewrite ^/([^/]+?)-sitemap([0-9]+)?.xml$ /index.php?sitemap=$1&sitemap_n=$2 last;
    # END Nginx Rewrites for Sitemaps
    listen 143.198.21X.1XX:443 ssl;
    ssl_certificate /etc/ssl/virtualmin/1671702822XX7723/ssl.combined;
    ssl_certificate_key /etc/ssl/virtualmin/1671702822117XX3/ssl.key;
}

Comment


Note: All Input Fields are required.