繁体   English   中英

如何从像“example.com/products/123/title-of-this-product”这样干净的 url $_GET['id']?

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

我希望我的 URL 看起来像这样:

example.com/products/123/title-of-this-product

实际的 URL 是这样的:

example.com/products.php?id=123&title=title-of-this-product

.htaccess文件正确解释了我的 URL,因此该页面上的用户只能看到干净的 URL。但是,如果我尝试在products.php页面上使用$_GET['id'] ,脚本会崩溃,因为它不会识别 URL 中的任何id

.htaccess代码:

Options +FollowSymLinks +MultiViews

RewriteEngine On
RewriteRule ^([0-9]+)(?:/([^/]*))?/?$ ./products.php?id=$1&title=$2 [L,NC]

products.php代码:

$product_id = isset($_GET['id']) ? $_GET['id'] : "Error! I can't find your product!";

如果我想要一个干净的 URL,如何保留 PHP 函数的 URL 参数?

你实际上在这里有2个问题......

  1. MultiViews (mod_negotiation 的一部分)已启用,它正在为products.php提供服务。
  2. 您的RewriteRule模式不正确,与请求的 URL 不匹配。
 Options +FollowSymLinks +MultiViews

您需要禁用MultiViews (您已明确启用它)。 为您的products.php文件(没有任何 URL 参数)提供服务的是 MultiViews(mod_negotiation 的一部分),而不是后面的 mod_rewrite 指令。 MultiViews 本质上允许以最小的努力使用无扩展名的 URL,但是,它可能是意外冲突的原因(使用 mod_rewrite)——就像在这种情况下一样。

您的RewriteRule指令实际上没有做任何事情。 如果.htaccess文件位于文档根目录中,则RewriteRule模式^([0-9]+)(?:/([^/]*))?/?$与请求的 URL ( /products/123/title-of-this-product ),所以该指令实际上根本没有被处理(尽管 MultiViews 仍然会覆盖它,即使它被处理了)。

试试这样:

# Disable MultiViews
Options +FollowSymLinks -MultiViews

RewriteEngine On
RewriteRule ^products/([0-9]+)(?:/([^/]*))?/?$ products.php?id=$1&title=$2 [L,NC]

您从与RewriteRule pattern匹配的 URL 路径的开头缺少products 如果没有products/在正则表达式的开头,它只会在您位于/products/子目录中时匹配,即。 /products/.htaccess RewriteRule指令与.htaccess文件本身的位置相匹配。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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