How to use Nginx and PHP-FPM to handle PHP redirects and rewrite rules?

To use Nginx and PHP-FPM to handle PHP redirects and rewrite rules, you can follow these steps:

  1. Install Nginx and PHP-FPM on your server. You can use package managers like apt or yum to install them.

  2. Configure Nginx to use PHP-FPM by editing the Nginx configuration file. The location of the configuration file may vary depending on your operating system, but it is typically located at /etc/nginx/nginx.conf or /etc/nginx/sites-available/default.

  3. Inside the http block of the Nginx configuration file, add the following lines to enable PHP support:

    server { ... location ~ \.php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php8.0-fpm.sock; # Use the correct PHP-FPM socket path } ... }

    This configuration block tells Nginx to pass PHP files to PHP-FPM for processing.

  4. Save the changes and exit the editor.

  5. Test your Nginx configuration by running the following command in the terminal:

    sudo nginx -t

    If the configuration is valid, you should see a message indicating success.

  6. Restart Nginx to apply the configuration changes:

    sudo systemctl restart nginx
  7. You can now use Nginx's rewrite and redirect directives in your server block or location block within the Nginx configuration file. Here's an example of how to configure a redirect and a rewrite rule:

    server { ... location /old-page { return 301 /new-page; # Redirect from /old-page to /new-page with a 301 status code } location /custom-url { rewrite ^/custom-url/(.*)$ /index.php?page=$1 last; # Rewrite /custom-url/abc to /index.php?page=abc } ... }

    In this example, the first location block redirects requests from /old-page to /new-page with a 301 status code. The second location block uses the rewrite directive to rewrite requests from /custom-url/abc to /index.php?page=abc.

  8. Save the changes to the Nginx configuration file and restart Nginx:

    sudo systemctl restart nginx

By following these steps, Nginx and PHP-FPM will handle PHP redirects and rewrite rules successfully.