【问题标题】:URL Rewriting with GET Vars使用 GET 变量重写 URL
【发布时间】:2016-05-08 14:10:15
【问题描述】:

我正在尝试使用 HTACCESS 重写我的目录中的所有 URL。我希望他们拥有相同的模型/架构。我在不同的网站上找到了一些代码,但是当我尝试它们时没有工作。

这是我想做的:

  • 我有这个网址:localhost/projects.php?id=1
  • 我希望它看起来像这样:localhost/projects/1

  • 这是另一个例子:

  • 我有这个网址:localhost/profile.php?id=1
  • 我希望它看起来像这样:localhost/profile/1
  • 换句话说,我想改变这个:

    • localhost/page.php?param=value&parm2=value2&...

    • localhost/page/value/value2/...

    有什么方法可以对我的所有页面执行此操作吗?我不知道应该在我的 HTACCESS 文件上写什么。

    【问题讨论】:

    • 您有实时域名吗?

    标签: php .htaccess url url-rewriting get


    【解决方案1】:

    首先使用 .htaccess 解析所有路由将是一件非常痛苦的事情,您应该只处理请求的文件及其参数,然后您应该解析 php 代码中的参数(这称为路由),然后您将为您创建路由申请。

    请检查下面的 .htaccess 规则;

    #These are our conditions to run our rewrite rule
    RewriteCond %{REQUEST_FILENAME} !-f #Request is not a file
    RewriteCond %{REQUEST_FILENAME} !-d #Request is not a directory
    RewriteCond %{REQUEST_FILENAME} !-l #Request is not a link
    #This is our rewrite rule   
    RewriteRule ^([a-zA-Z0-9]*)?/(.*)$ $1.php/$2 [QSA,L] #QSA means QueryStringAppend modify according to your need, L means this is my last rule which same with stop processing rewrite rules
    

    你应该有一个类似下面的 php 代码来处理你的路由请求

    <?PHP
        $requestedPath = trim($_SERVER["PHP_SELF"],"/");
        $request = explode("/",$requestedPath,2);
        $requestFileName = $request[0]; //This is your requested file as you know already from .htaccess
        $requestParams = $request[1]; //You should parse this params according to your routing need
    ?>
    

    希望这些信息可以帮助您了解路由和通用 .htaccess 规则。

    PS:您的请求将类似于 www.example.com/myaction/first-parameter/second-parameter/third-parameter,对于此示例,$requestParams 将是 first-parameter/second-parameter/third-parameter

    【讨论】:

    • 在 apache 中不允许以 // 开头的评论。
    • 不,QSA 不代表 QueryStringAllowed,它代表 Query String Append(另见:RewriteFlags/QSA
    • @MikeRockett 哦,我记得它是允许的查询字符串,谢谢您提供正确的信息
    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 2013-04-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多