Table of Contents
If you’re diving into Laravel development, setting it up on an Ubuntu server with Nginx can seem a bit overwhelming at first. But once you’ve got it running, Laravel (combined with Nginx) creates a powerful, efficient environment for your web applications.
Here, we’ll walk you through every step—from installing Laravel on your Ubuntu machine to configuring Nginx to serve your Laravel app properly. Don’t worry if you’re new to the Laravel Nginx configuration; we’ll break it down simply and straightforwardly, making sure you get your Laravel app live and running smoothly on Nginx.
Whether you’re handling this setup for yourself or working with a web development company, this guide will help ensure everything runs smoothly. Let’s get started!
Installing and Configuring Laravel with Nginx
Installation and configuration of Laravel with Nginx may sound a bit technical, but don’t worry—we’ll break it down step by step.
From setting up the server environment to installing Laravel and configuring Nginx, we’ll make sure everything is laid out clearly.
Step 1: Set Up PHP for Laravel
Before we can install Laravel, there are a few PHP modules you’ll need to install to ensure everything works smoothly. These modules help Laravel handle tasks like character encoding, XML parsing, and precise math operations.
Start by updating your package manager cache to make sure you’re getting the latest versions of the software:
sudo apt update
Next, install the required PHP modules with the following command:
sudo apt install php-mbstring php-xml php-bcmath php-curl
This installs php-mbstring, php-xml, php-bcmath, and php-curl, which are necessary for Laravel to run. Now that these modules are installed, your system is ready to move forward with Laravel’s installation through Composer. But first, let’s create a database for the application.
Step 2: Create and Configure Your Laravel Database
For this example, we’ll create a simple book collection app that tracks books you want to read and those you’ve already finished. We’ll store this information in a MySQL database table called books, with columns for the book’s title, author, and whether you’ve read it (read_status).
Start by logging into MySQL as the root user:
sudo mysql
Now, create a new database called booklist:
CREATE DATABASE booklist;
Next, create a new MySQL user who will interact with the booklist database. We’ll set the user to use mysql_native_password for compatibility with PHP. Replace ‘password’ with a secure password of your choice:
CREATE USER 'booklist_user'@'%' IDENTIFIED WITH mysql_native_password BY 'password';
Grant this user full permissions over the booklist database:
GRANT ALL ON booklist.* TO 'booklist_user'@'%';
Now, exit the MySQL console:
exit
To test that the new user has proper permissions, log in again using the new user’s credentials:
mysql -u booklist_user -p
Enter the password you set for booklist_user when prompted. After logging in, check to ensure that the booklist database exists:
SHOW DATABASES;
You should see:
+--------------------+
| Database |
+--------------------+
| information_schema |
| booklist |
+--------------------+
Now, create a table named books in the booklist database to store your collection. This table will have four columns: an ID (id), the book title (title), the author (author), and the read status (read_status):
CREATE TABLE booklist.books (
id INT AUTO_INCREMENT,
title VARCHAR(255),
author VARCHAR(255),
read_status BOOLEAN,
PRIMARY KEY(id)
);
Next, populate the table with some sample book data:
INSERT INTO booklist.books (title, author, read_status)
VALUES ("The Great Gatsby", "F. Scott Fitzgerald", false),
("1984", "George Orwell", true),
("To Kill a Mockingbird", "Harper Lee", true),
("The Catcher in the Rye", "J.D. Salinger", false),
("Moby Dick", "Herman Melville", false);
To verify that the data has been added, run the following:
SELECT * FROM booklist.books;
You should see this output:
+----+-------------------------+---------------------+-------------+
| id | title | author | read_status |
+----+-------------------------+---------------------+-------------+
| 1 | The Great Gatsby | F. Scott Fitzgerald | 0 |
| 2 | 1984 | George Orwell | 1 |
| 3 | To Kill a Mockingbird | Harper Lee | 1 |
| 4 | The Catcher in the Rye | J.D. Salinger | 0 |
| 5 | Moby Dick | Herman Melville | 0 |
+----+-------------------------+---------------------+-------------+
After confirming that your data was successfully inserted, you can exit the MySQL console:
exit
Now that the database and table are ready, you can connect your Laravel application to this new database for the book collection app.
Step 3: Get Started with Laravel
Now that your database is set up, the next step is to create a new Laravel application using Composer’s create-project command. This command will set up a fresh Laravel project, which we’ll use to build our book collection app.
Start by navigating to your user’s home directory:
cd ~
Then, run the following command to create a new Laravel project in a directory called booklist:
composer create-project --prefer-dist laravel/laravel booklist
You should see output similar to the following:
Creating a "laravel/laravel" project at "./booklist"
Installing laravel/laravel (v9.1.5)
- Installing laravel/laravel (v9.1.5): Extracting archive
Created project in /home/your_user/booklist
> @php -r "file_exists('.env') || copy('.env.example', '.env');"
Loading composer repositories with package information
Updating dependencies
...
Package manifest generated successfully.
78 packages you are using are looking for funding.
Use the `composer fund` command to find out more!
> @php artisan vendor:publish --tag=laravel-assets --ansi --force
No publishable resources for tag [laravel-assets].
Publishing complete.
> @php artisan key:generate --ansi
Application key set successfully.
Once the installation completes, move into the booklist application’s directory and use Laravel’s Artisan command-line tool to verify that everything has been installed correctly:
cd booklist
php artisan
You should see output like this:
Laravel Framework 9.8.1
Usage:
command [options] [arguments]
Options:
-h, --help Display help for the given command. When no command is given display help for the list command
-q, --quiet Do not output any message
-V, --version Display this application version
...
This confirms that Laravel has been installed correctly and Artisan (Laravel’s command-line tool) is working as expected. But before you can access your application, you’ll need to configure it to connect to the database you created earlier.
Need help with Laravel and Nginx configuration?
Step 4: Adjust Laravel Settings
Laravel stores its configuration settings in the config directory within the application’s root directory. Additionally, the .env file stores environment-specific configuration, such as database credentials, and these settings take precedence over values defined in the configuration files.
The .env file contains sensitive information, like database credentials and application keys, so it’s important not to share it publicly.
We need to modify the .env file to configure the connection to the booklist database.
Start by opening the .env file with a command-line text editor, such as nano:
nano .env
You will see several variables in this file. Here’s a breakdown of the ones that need to be configured for your app:
- APP_NAME: The name of your application.
- APP_ENV: The environment the application is running in (development, production, etc.).
- APP_KEY: A unique key used for generating salts and hashes (automatically generated during the Laravel installation).
- APP_DEBUG: Whether to display detailed error messages (true for development, false for production).
- APP_URL: The base URL for the application.
- DB_DATABASE: The name of the database.
- DB_USERNAME: The database username.
- DB_PASSWORD: The database password.
For our book collection app, modify these variables as follows:
APP_NAME=BookList
APP_ENV=development
APP_KEY=base64:GENERATED_APPLICATION_KEY
APP_DEBUG=true
APP_URL=http://your_domain_or_IP
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=booklist
DB_USERNAME=booklist_user
DB_PASSWORD=password
Replace your_domain_or_IP with the actual domain name or IP address where your Laravel application will run. Also, make sure to replace the APP_KEY with the one generated for your application during the installation process, and enter the correct MySQL credentials.
Once you’ve updated the .env file, save and close it. If you’re using nano, press CTRL + X, then Y, and hit Enter to confirm the changes.
At this point, your Laravel application is set up to connect to the database. However, we still need to configure the web server to allow access to the application from a browser. In the next step, we’ll configure Nginx to serve your Laravel app.
Step 5: Configure Nginx for Laravel
Now that we’ve installed Laravel in the /var/www directory, let’s configure Nginx to serve your book collection application.
First, move your Laravel application to the /var/www directory:
sudo mv ~/booklist /var/www/booklist
Next, ensure that the web server user has the appropriate permissions for the storage and cache directories:
sudo chown -R www-data:www-data /var/www/booklist/storage
sudo chown -R www-data:www-data /var/www/booklist/bootstrap/cache
With the application files in place, we’ll set up Nginx to serve the content. Create a new virtual host configuration file:
sudo nano /etc/nginx/sites-available/booklist
Add the following configuration:
server {
listen 80;
server_name server_domain_or_IP;
root /var/www/booklist/public;
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
index index.html index.htm 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.1-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
}
location ~ /\.(?!well-known).* {
deny all;
}
}
Replace server_domain_or_IP with your actual domain name or IP address. Save and close the file.
Activate the new virtual host configuration by creating a symbolic link to sites-enabled:
sudo ln -s /etc/nginx/sites-available/booklist /etc/nginx/sites-enabled/
Check the configuration for syntax errors:
sudo nginx -t
You should see:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Apply the changes by reloading Nginx:
sudo systemctl reload nginx
Visit your server’s domain name or IP address in a browser:
http://server_domain_or_IP
You should see the Laravel welcome page, confirming that Nginx is correctly serving your application.
Step 6: Customize Your Laravel Homepage
With Laravel running and Nginx configured, it’s time to customize the main page to display data from your book collection database.
Open the routes/web.php file:
nano routes/web.php
Replace the existing code with:
<?php
use Illuminate\Support\Facades\DB;
Route::get('/', function () {
$read = DB::select('select * from books where read = ?', [1]);
$toRead = DB::select('select * from books where read = ?', [0]);
return view('booklist', ['read' => $read, 'toRead' => $toRead]);
});
Save and close the file. Next, create the view to display the data. Open a new file in resources/views:
nano resources/views/booklist.blade.php
Add the following content:
<html>
<head>
<title>Book List</title>
</head>
<body>
<h1>My Book Collection</h1>
<h2>Books I've Read</h2>
<ul>
@foreach ($read as $book)
<li>{{ $book->title }}</li>
@endforeach
</ul>
<h2>Books I Want to Read</h2>
<ul>
@foreach ($toRead as $book)
<li>{{ $book->title }}</li>
@endforeach
</ul>
</body>
</html>
Save and close the file. Reload your browser, and you should see a page listing books categorized by those you’ve read and those you want to read.
Congratulations! You’ve successfully set up your Laravel application with Nginx and customized it to display data from your book collection database.
FAQs on How To Install and Configure Laravel with Nginx on Ubuntu
- Step 1: Navigate to Your Project Directory
- Step 2: Install Dependencies
- Step 3: Set Up the Environment File
- Step 4: Generate Application Key
- Step 5: Run Migrations
- Step 6: Start the Laravel Development Server
Final Thoughts
Congrats! You’ve successfully installed and configured Laravel with Nginx on Ubuntu.
Here’s a quick recap:
- Installed PHP Modules: You set up the necessary PHP extensions to support Laravel.
- Created a Database: You set up a MySQL database and user-tailored for your Laravel application.
- Built a New Laravel App: You created a Laravel project and confirmed its installation.
- Configured Laravel: You adjusted the Laravel configuration to connect to your database.
- Set Up Nginx: You moved your Laravel project to the right directory and configured Nginx to serve your application.
- Customized Your Main Page: You modified Laravel’s main route to display data from your database.
With everything set up, you can now start developing your application or deploy it for others to use.
If you’re looking to take your project to the next level or need expert help with Laravel and Nginx, trust our web development services. Get in touch with us to explore how we can help bring your vision to life with tailored web development solutions.