【问题标题】:htaccess get one parameter or two depending of the url PHPhtaccess 根据 url PHP 获取一两个参数
【发布时间】:2017-12-18 10:49:50
【问题描述】:

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

我的索引 php 文件:

<?php

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

?>

这样,用户可以访问我的网站并编写如下网址:

http://localhost/loremipsum?page=home

http://localhost/loremipsum?page=help

但为了获得更清晰的网址,我编辑了我的 .htaccess 文件以获取类似以下网址:

http://localhost/loremipsum/home

http://localhost/loremipsum/help

.htaccess: 重写引擎开启 RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d 重写规则 ^(.*) /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]

更新:

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

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

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

【问题讨论】:

    标签: php .htaccess


    【解决方案1】:

    您可以像这样制定重写规则:

    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 />";
    
    }
    
    ?>
    

    【讨论】:

    • 嘿,谢谢伙计,我不知道我重写规则的方式是导致只有一个 get 变量中的所有参数,该 php 代码是关键,无需修改其他任何内容,这是迄今为止我发现的最简单的方法。非常感谢您的宝贵时间:)
    猜你喜欢
    • 2015-04-18
    • 2020-06-29
    • 2014-06-04
    • 2019-01-20
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 2018-03-05
    相关资源
    最近更新 更多