How to configure Nginx to handle clean URLs for PHP applications?

To configure Nginx to handle clean URLs for PHP applications, you need to follow these steps:

  1. Edit the Nginx configuration file for your site. Typically, this file is located at /etc/nginx/sites-available/your-site.conf.

  2. Inside the server block, add the following location block to handle PHP requests:

    location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; }

    Note: The fastcgi_pass line may vary depending on the PHP version you are using. Make sure to check the correct socket path.

  3. Add another location block to handle clean URLs. For this, you need to use the try_files directive, which checks if the requested file exists and if not, passes the request to the PHP script. Add the following code after the previous location block:

    location / { try_files $uri $uri/ /index.php?$args; }
  4. Save the changes to the configuration file.

  5. Test the Nginx configuration for any syntax errors by running the following command:

    sudo nginx -t

    If there are no errors, restart Nginx to apply the changes:

    sudo systemctl restart nginx

These steps will configure Nginx to handle clean URLs for your PHP application.