Php 当两个文件位于同一文件夹中时,识别重写规则的可能方法?

Php 当两个文件位于同一文件夹中时,识别重写规则的可能方法?,php,apache,.htaccess,Php,Apache,.htaccess,好吧,这听起来可能是stackoverflow上最糟糕的问题,但就是这里 在文件夹中,我有以下文件: product.php category.php 要显示产品,我键入domain.com/offers/product.php?id=1和要显示类别,我键入domain.com/offers/category.php?id=1 因为这个url看起来很难看,所以我使用.htaccess重写了product.php RewriteEngine On RewriteRule ^([a-z0-9]+)

好吧,这听起来可能是stackoverflow上最糟糕的问题,但就是这里

在文件夹
中,我有以下文件:

product.php
category.php
要显示产品,我键入
domain.com/offers/product.php?id=1

要显示类别,我键入
domain.com/offers/category.php?id=1

因为这个url看起来很难看,所以我使用.htaccess重写了product.php

RewriteEngine On
RewriteRule ^([a-z0-9]+)?$ product.php?id=$1 [NC,L]
这给了我一个
domain.com/offers/1

因为
product.php
category.php
在同一个文件夹中,并且都得到一个数字变量,这意味着它将无法正确执行

因此,一种可能的方法是为
category.php
设置一个
slug
,并为
product.php
保留
id
,然后为其编写一些代码

我的问题是,这是唯一的办法吗

更新

我没有试过,但是如果我有一个是
product.php?pid=1
,另一个是
category.php?cid=1

你需要在显示的URL中有所不同。类似于

RewriteRule ^([a-z0-9]+)$ product.php?id=$1
RewriteRule ^category/([a-z0-9]+)$ category.php?id=$1

您需要在URL中区分它们。此方案将URL转换为:

example.com/offers/category/1
example.com/offers/product/99
通过以下方式完成:

RewriteEngine On
RewriteRule ^offers/(product|category)/([a-z0-9]+)?$ $1.php?id=$2 [NC,L,QSA]
RewriteEngine On
RewriteRule ^offers/p([a-z0-9]+)?$ product.php?id=$1 [NC,L,QSA]
RewriteRule ^offers/c([a-z0-9]+)?$ category.php?id=$1 [NC,L,QSA]
第一组
(产品|类别)
捕获目标脚本,该脚本被翻译为
$1.php
。第二个组被转换为关联的id

更新 您不必让它们显示为单独的目录
/products,/categories
,但您必须有一些区分它们的方法。您可以将
p
c
放在ID号的开头:

example.com/offers/c1
example.com/offers/p99
通过以下方式完成:

RewriteEngine On
RewriteRule ^offers/(product|category)/([a-z0-9]+)?$ $1.php?id=$2 [NC,L,QSA]
RewriteEngine On
RewriteRule ^offers/p([a-z0-9]+)?$ product.php?id=$1 [NC,L,QSA]
RewriteRule ^offers/c([a-z0-9]+)?$ category.php?id=$1 [NC,L,QSA]

或者您可以将它们扩展到

问题不在于页面的真实URL(pid/cid而不是id),而在于用户看到的URL。在这两种情况下,听起来您都在试图让
domain.com/offers/???
重定向到产品或类别,但实际情况并非如此;在显示的URL中需要有一些东西告诉重写规则它应该去哪里。。。当然希望这一切都有意义。@sdleihsirhc。谢谢。这意味着product.php将从
domain.com/offers/1
访问,category.php将从
domain.com/category/1
访问?它必须位于不同的文件夹中吗?类别文件夹和产品文件夹?