htaccess 获取一个或两个参数,具体取决于 URL PHP



首先:如果你对这个问题有更好的标题,请告诉我。 您好,我有一个使用 get 变量加载内容的网站。 让我向你解释一下。

我的索引 php 文件:

<?php
#check if get parameter page exists 
#check if file exists
require $_GET['page] . '.php'; //if it exists require its content    
?>

这样,用户可以转到我的网站并编写如下所示的URL:

http://localhost/loremipsum?page=home
http://localhost/loremipsum?page=help

但是为了获得一个更干净的网址,我编辑了我的 .htaccess 文件以获取如下网址:

http://localhost/loremipsum/home
http://localhost/loremipsum/help

.htaccess: 重写引擎打开 重写库/RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*(/loremipsum/?pg=$1 [L]

但是我到了需要其他参数的地步,对于下一个 url,我希望将userpreferences作为page参数,something作为fav参数

像这样的网址可以工作:

http://localhost/loremipsum/userpreferences&fav=something

但目标是获得这样的网址:

http://localhost/loremipsum/userpreferences/something

问题是我尝试过的一切都不起作用,这就是我认为它应该起作用但事实并非如此:

RewriteRule ^(.*)/userpreferences/(a-zA-Z0-9)+ /loremipsum/?pg=$1&fav=$2 [L]

更新:

我知道只有当页面参数等于用户首选项时才应该应用此规则,并且我正在考虑这样做

RewriteRule ^userpreferences/(a-zA-Z0-9)+ /loremipsum/?pg=userpreferences&fav=$1 [L]

但它不起作用,似乎用户首选项不会是一个字符串,我收到服务器错误。

您可以像这样创建重写规则:

RewriteRule ^(.*)$ index.php?parameter=$1 [NC]

然后你得到:

index.php?parameter=param/value/param/value

从浏览器中,您可以获得:

http://localhost/parameter/param/value/param/value

在 PHP 文件中,您可以访问您的参数:

<?php
$parameter = explode( "/", $_GET['parameter'] );
for($i = 0; $i < count($parameter); $i+=2) {
echo $parameter[$i] ." has value: ". $parameter[$i+1] ."<br />";
}
?>

最新更新