Convert URLs to a series of query string parameters. Can be used to allow ‘pretty’ SEO-friendly URL structures to be leveraged without changing the underlying web application’s expectation that parameters and filters will be passed as query string key/value pairs.

Rewrite Simple URLs

Consider the following URL to a user’s profile page:

  • https://example.com/users/fred (with or without a final trailing slash /)

And this needs to be exposed to the web application as:

  • https://example.com/users.php?username=fred

Simply add the following to .htaccess:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^users/(.*?)/?$ /users.php?username=$1 [L]

Rewrite Product Browsing URLs

Consider the following series of URLs, part of a product browsing scheme:

  • /products/
  • /products/mens/
  • /products/mens/clothing/
  • /products/mens/clothing/sportswear/
  • /products/mens/clothing/sportswear/sale/

This structure can be rewritten to convert the ‘directory’ strings to query string parameters thereby making them available to the underlying web application as url params. Add the following rule to .htaccess:

 RewriteRule ^products/?([^/]*)/?([^/]*)/?([^/]*)/?([^/]*)/?  /products.php?dept=$1&cat=$2&subcat=$3&status=$4 [PT]

This would cause requests to these URLs to be transparently rewritten to:

  • /products/
    • /products.php?dept=&cat=&subcat=&status=
  • /products/mens/
    • /products.php?dept=mens&cat=&subcat=&status=
  • /products/mens/clothing/
    • /products.php?dept=mens&cat=clothing&subcat=&status=
  • /products/mens/clothing/sportswear/
    • /products.php?dept=mens&cat=clothing&subcat=sportswear&status=
  • /products/mens/clothing/sportswear/sale/
    • /products.php?dept=mens&cat=clothing&subcat=sportswear&status=sale

This rule uses the PT (PassThrough) flag, allowing aliases which may exist to be honored. In many situations it can be omitted.