الدورات

title


How to Set Up Nginx for Laravel (Even If You Already Have Apache Running)

How to Set Up Nginx for Laravel (Even If You Already Have Apache Running)

Introduction

Laravel is one of the most popular PHP frameworks, known for its clean structure and scalability. While Apache is a common web server for PHP, Nginx is often preferred for its high performance, low memory usage, and ability to handle large numbers of concurrent connections.

In this article, you’ll learn how to:

  • Install and configure Nginx for Laravel.
  • Serve Laravel with PHP-FPM (FastCGI Process Manager).
  • Switch from Apache to Nginx safely, or run both side-by-side.

This tutorial works on Ubuntu/Debian systems but can be easily adapted for CentOS or other Linux distributions.


Step 1: Install Nginx

First, make sure your system packages are up-to-date:

sudo apt update && sudo apt upgrade -y

Then install Nginx:

sudo apt install nginx -y

Once installed, start and enable the service:

sudo systemctl start nginx
sudo systemctl enable nginx

Check that Nginx is running:

sudo systemctl status nginx

You should see “active (running)”.


Step 2: Install PHP and Required Extensions

Laravel requires PHP and several extensions. If you already have PHP installed for Apache, you can reuse it — but make sure you have PHP-FPM, not just mod_php.

Install PHP-FPM and common Laravel dependencies:

sudo apt install php-fpm php-mbstring php-xml php-bcmath php-json php-zip php-curl php-mysql -y

Check the version and socket path:

php -v
sudo systemctl status php*-fpm

Note the socket file path, usually something like:

/run/php/php8.2-fpm.sock

You’ll need this later for your Nginx configuration.


Step 3: Configure Nginx for Laravel

Assuming your Laravel project is located in:

/var/www/laravel_project

Create a new Nginx configuration file:

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

Paste the following configuration:

server {
    listen 80;
    server_name yourdomain.com www.yourdomain.com;
    root /var/www/laravel_project/public;

    index index.php index.html index.htm;

    access_log /var/log/nginx/laravel_access.log;
    error_log /var/log/nginx/laravel_error.log;

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

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

    location ~ /\.ht {
        deny all;
    }
}

Save and exit.

Enable the site and reload Nginx:

sudo ln -s /etc/nginx/sites-available/laravel_project /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

Step 4: Adjust File Permissions

Make sure your Laravel storage and cache directories are writable:

sudo chown -R www-data:www-data /var/www/laravel_project
sudo chmod -R 775 /var/www/laravel_project/storage
sudo chmod -R 775 /var/www/laravel_project/bootstrap/cache

Step 5: Test the Application

Visit your domain or IP address in a browser:

http://yourdomain.com

If everything is configured correctly, you should see your Laravel homepage.

If you see a 403 or 404 error, double-check:

  • The root path points to /public
  • File permissions are correct
  • PHP-FPM is running

Step 6: Handling Apache Conflict (If You Already Have Apache)

If you already have a website using Apache, there are two options:

Option 1: Stop Apache and Fully Switch to Nginx

If you plan to replace Apache entirely:

sudo systemctl stop apache2
sudo systemctl disable apache2
sudo systemctl start nginx

Make sure Nginx is listening on port 80 and Apache is stopped:

sudo lsof -i -P -n | grep LISTEN

Option 2: Run Apache and Nginx Together

If you want both web servers running on the same machine (for example, one handles certain sites), you must change Nginx to listen on a different port (like 8080):

Edit your Laravel site config:

server {
    listen 8080;
    server_name yourdomain.com;
    root /var/www/laravel_project/public;
    ...
}

Then access your Laravel app via:

http://yourdomain.com:8080

Or use a reverse proxy setup (e.g., Apache on 80 → Nginx on 8080).


Step 7: Enable SSL with Certbot (Optional but Recommended)

Install Certbot:

sudo apt install certbot python3-certbot-nginx -y

Then run:

sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com

Certbot automatically edits your Nginx config and enables HTTPS.


Step 8: Optimize Nginx for Laravel

For better performance, you can add caching headers and gzip compression.

Open your Nginx config and add inside the server {} block:

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    expires 30d;
    add_header Cache-Control "public, no-transform";
}

gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml+rss;

Reload Nginx:

sudo systemctl reload nginx

Step 9: Troubleshooting Common Issues

ErrorCauseFix403 ForbiddenWrong permissions or root pathCheck /public path and permissions502 Bad GatewayPHP-FPM not runningRestart PHP-FPM: sudo systemctl restart php*-fpmNo responsePort conflictStop Apache or change Nginx portSSL renewal failsCertbot misconfigRun sudo certbot renew --dry-run to test

Conclusion

Setting up Nginx for Laravel gives you better speed, scalability, and security. Whether you’re migrating from Apache or running both, the process is straightforward once you understand how Laravel interacts with PHP-FPM and Nginx configuration files.