How to configure Nginx to handle URL rewriting and redirection?

To configure Nginx to handle URL rewriting and redirection, follow these steps:

  1. Open the Nginx configuration file using a text editor. The file is usually located at /etc/nginx/nginx.conf or /etc/nginx/conf.d/default.conf.

  2. Find the server block for the specific website or domain you want to configure. It typically starts with server { and ends with }.

  3. Inside the server block, add the following lines to enable rewrite rules:

    location / { try_files $uri $uri/ @rewrites; } location @rewrites { rewrite ^/(.*)$ /index.php?page=$1 last; }

    The above example assumes you want to rewrite all URLs to a PHP script called index.php, passing the URL as a parameter.

  4. To redirect a specific URL or pattern to another URL, add a new location block inside the server block:

    location /old-url { return 301 /new-url; }

    Replace /old-url with the original URL that you want to redirect, and /new-url with the destination URL.

  5. Save the configuration file and exit the text editor.

  6. Test the configuration for syntax errors by running sudo nginx -t in the terminal. If there are no errors, proceed to the next step.

  7. Restart the Nginx server to apply the changes. The command to restart Nginx depends on your operating system. Common commands include sudo service nginx restart or sudo systemctl restart nginx.

Now your Nginx server should be properly configured to handle URL rewriting and redirection.