简体   繁体   中英

How to $_GET['id'] from a clean url like "example.com/products/123/title-of-this-product"?

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?

You actually have 2 problems here...

  1. MultiViews (part of mod_negotiation) is enabled and it's this that is serving products.php .
  2. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM