How to configure Nginx to serve static files efficiently alongside PHP-FPM?

To configure Nginx to serve static files efficiently alongside PHP-FPM, you can follow these steps:

  1. Install Nginx and PHP-FPM on your server if you haven't already.

  2. Open the Nginx configuration file for your site. This file is usually located at /etc/nginx/sites-available/default or /etc/nginx/nginx.conf.

  3. Find the server block and add the following location block inside it:

    location ~ \.(jpg|jpeg|png|gif|ico|css|js)$ { try_files $uri /index.php$is_args$args; access_log off; expires max; }

    This location block specifies the file extensions you want Nginx to handle as static files. It first tries to serve the file directly and if it doesn't exist, it will pass the request to PHP-FPM.

  4. Uncomment or add the following line in the location ~ \.php$ block in the server configuration:

    include snippets/fastcgi-php.conf;

    This line includes the PHP configuration file, which is necessary for PHP-FPM to work correctly.

  5. Save the configuration file and restart Nginx to apply the changes:

    sudo service nginx restart

Now, Nginx will efficiently serve the specified static files directly while passing other requests to PHP-FPM. This setup can help improve the performance of your PHP applications by offloading the serving of static files to Nginx.