【问题标题】:htaccess get the first directory of a linkhtaccess 获取链接的第一个目录
【发布时间】:2020-12-24 04:11:01
【问题描述】:

我目前在一个 php 网站上工作,我对 htaccess 重写规则和条件非常陌生。我的问题是如何从链接中只获取第一个目录?

例如,我有一个链接“example.com/page1/page2/?something=something”,我需要输出为 page1,以便将其重定向到 index.php?p=page1

还有我会怎么做才能得到“page2”或“?something=something”的输出?所以在这种情况下,我会将其重定向到 index.php?p=page1&ap=page2&something=something

我知道理论上我可以使用:

RewriteRule ^page1/page2$ index.php?p=page1&ap=page2

但在这种情况下,我无法预测 page1 和 page2 会是什么,所以假设它就像一个变量:

RewriteRule ^{somevariable}/{someothervariable}$ index.php?p={somevariable}&ap={someothervariable}

在这种情况下,输出将是“index.php?p=page1&ap=page2”。

我试图在网络上搜索这个,但我真的不知道要搜索什么。

提前致谢!

【问题讨论】:

    标签: php .htaccess mod-rewrite


    【解决方案1】:

    您确实可以使用RewriteRule 来解析网址...

    RewriteRule ^(.*?)/(.*)/?$ /index.php?p=$1&ap=$2 [L,QSA]
    
    ^               : Match the start of the string
     (.+?)          : Match any character one or more times; non-greedy
          /         : Match a slash
           (.+)     : Match any character one or more times
               /?   : Optionally match a slash
                 $  : Match the end of the string
    
    L               : Stops processing rules
    QSA             : Append the original query string
    

    示例

    http://www.somewebsite.com/page1/page2?id=1435
    
    print_r($_GET);
    
    /*
    
    Array
    (
        [p]  => page1
        [ap] => page2
        [id] => 1435
    )
    
    */
    

    【讨论】:

    • 非常感谢!这正是我需要的方式!
    • @RobertsLacis 很高兴我能帮上忙!如果这解决了您的问题,您可以通过单击旁边的复选标记将答案标记为已接受。
    猜你喜欢
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 2016-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多