I'd like my URL to look like this:
example.com/products/123/title-of-this-product
The actual URL is this:
example.com/products.php?id=123&title=title-of-this-product
The .htaccess
file correctly interprets my URLs so that users who are on this page only see the clean URL. However, if I try to use $_GET['id']
on the products.php
page, the script crashes because it doesn't recognize any id
in the URL.
.htaccess
code:
Options FollowSymLinks MultiViews
RewriteEngine On
RewriteRule ^([0-9] )(?:/([^/]*))?/?$ ./products.php?id=$1&title=$2 [L,NC]
products.php
code:
$product_id = isset($_GET['id']) ? $_GET['id'] : "Error! I can't find your product!";
How can I retain the URL parameters for PHP functions if I want a clean URL?
CodePudding user response:
You actually have 2 problems here...
MultiViews
(part of mod_negotiation) is enabled and it's this that is servingproducts.php
.- Your
RewriteRule
pattern is incorrect and won't match the requested URL.
Options FollowSymLinks MultiViews
You need to disable MultiViews
(you have explicitly enabled it). It is MultiViews (part of mod_negotiation) that is serving your products.php
file (without any URL parameters), not the mod_rewrite directive that follows. MultiViews essentially allows extensionless URLs with minimal effort, however, it can be the cause of unexpected conflicts (with mod_rewrite) - as in this case.
Your RewriteRule
directive is not actually doing anything. If the .htaccess
file is located in the document root then the RewriteRule
pattern ^([0-9] )(?:/([^/]*))?/?$
does not match the requested URL (/products/123/title-of-this-product
), so the directive is not actually processed at all (although MultiViews would still override this even if it did).
Try it like this instead:
# Disable MultiViews
Options FollowSymLinks -MultiViews
RewriteEngine On
RewriteRule ^products/([0-9] )(?:/([^/]*))?/?$ products.php?id=$1&title=$2 [L,NC]
You were missing products
from the start of the URL-path matched by the RewriteRule
pattern. Without products/
at the start of the regex it would only match if you are in a /products/
subdirectory, ie. /products/.htaccess
. The RewriteRule
directive matches relative to the location of the .htaccess
file itself.