Deploying a Laravel application with Nginx involves setting up the web server to correctly handle the incoming requests and serve your application. Here’s a step-by-step guide to deploying a Laravel application with Nginx:
1- Server setup:
Assuming you have a server with Ubuntu installed, you can start by updating your system:
sudo apt update
sudo apt upgrade
2- Install required software:
Install PHP, Composer, Nginx, and other necessary packages:
sudo apt installcomposer nginx php-fpm php-mysqlphp-json php-mbstring php-xml php-zip php-gd php-curl
3- Confire Nginx:
Create an Nginx server block configuration for your Laravel application. Create a new file in the /etc/nginx/sites-available/
directory (you might need to adjust paths and filenames according to your server setup):
sudo nano /etc/nginx/sites-available/default
- Paste the following configuration:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/html/your-laravel-project/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;
}
}
- Enable the site configuration:
sudo ln -s /etc/nginx/sites-available/laravel /etc/nginx/sites-enabled/
- Test the Nginx configuration:
sudo nginx -t
- Restart Nginx:
sudo systemctl restart nginx
4- Deploy Laravel Application:
Upload your Laravel application code to the server. You can use SCP, SFTP, or any other method you prefer.
Set appropriate permissions for the Laravel storage and bootstrap cache directories:
cd /var/www/your_laravel_app
sudo chown -R www-data:www-data storage bootstrap/cache
5- Configure Laravel Environment:
- Copy the
.env
file and configure it with your production settings:
cp .env.example .env
nano .env
- Generate an application key:
php artisan key:generate
6- Set Up Database:
- If your application uses a database, create the database and update your
.env
file with the database credentials.
7- Run Migrations:
Run your application’s migrations to set up the database tables:
- Run your application’s migrations to set up the database tables:
php artisan migrate
8- Restart PHP-FPM:
- Restart the PHP-FPM service: (Adjust version if necessary)
sudo systemctl restart php7.4-fpm
Top comments (0)