Rewrite URLs Example
The following example demonstrates how to use URL rewrites in your application.
Introduction
In some cases, you may want to have cleaner URLs for your website.
This can be achieved by using URL rewrites. This is an example of how to set up URL rewrites
using an .htaccess file, which is commonly used with Apache web servers.
Example url structure
Let's say you have a product cataog where each product has it's own page.
https://example.com/product?id=123
Your SEO guru told you that product URLs should be cleaner and more SEO friendly if they look like:
https://example.com/prod/123
Setting up the .htaccess file
To achieve this, you can add the following rules to your .htaccess file in the
/public directory:
RewriteEngine On
##### START: Rewrite rules for product URLs #####
# Step 1: redirect /product?id=123 to /product/123
RewriteCond %{THE_REQUEST} product\?id=([^&\ ]+)
RewriteRule ^ /prod/%1? [L,R=301]
# Step 2: Rewrite /product/123 to index.php?__route=product&id=123
RewriteRule ^prod/([^/]+)/?$ index.php?__route=product&id=$1 [QSA,L]
##### END: Rewrite rules for product URLs #####
# Route everything else through index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
Detailed explanation:
Step 1:
Redirect any request from the old URL format /product?id=123 to the new
format /prod/123.
if someone access:
https://example.com/product?id=123 -> https://example.com/prod/123
Step 2:
Rewrites the new URL format /prod/123 to the internal script
index.php?__route=product&id=123, allowing your application to handle the request
appropriately.
The second part is most important as without it the new url would result in 404 page.
The most important part here is the __route={action} query parameter, which tells
your application that the request is for the product action in the example above.