dtch60248 2018-06-14 22:26
浏览 61
已采纳

htaccess将多查询字符串重写为路径

How would i go about changing the query string

file.php?id=number&string=some-words

into this

file/number/some-words/

I know this has been asked a million times before, but I've looked at a number of solutions on here and they were all single query based (as in just ?something and not ?something&something-else).

Also once rewritten, does the php still read the original page query-string when using $_GET or $_REQUEST etc... even though it now appears as a path?

Any help is appreciated.

Thanks.

  • 写回答

2条回答 默认 最新

  • dsmnedc798226 2018-06-14 23:05
    关注

    RewriteRule takes a regular expression which can be as complicated as you want it followed by the real URL that will load your file. You put parenthesis around the parts you want to capture in the regex and can reference those with $1 for first group, $2 for second group and so on in the URL part. For example:

    RewriteRule ^(\w+)/(\d+)/(.*)$ index.php?file=$1&id=$2&words=$3
    

    This would match 3 groups:

    1. letters/numbers up to the first slash
    2. some numbers up to the second slash
    3. anything after that including additional slashes

    And those can be referenced by $1, $2, $3 as seen in the second part with index.php.

    The only issue with this though is that if you are missing any one part, the pattern in the rule won't match. So you either need to have a separate rule for each variant:

    #matches all 3 parts
    RewriteRule ^(\w+)/(\d+)/(.*)$ index.php?file=$1&id=$2&words=$3
    #matches the first 2 parts
    RewriteRule ^(\w+)/(\d+)$ index.php?file=$1&id=$2
    #matches just the first part
    RewriteRule ^(\w+)$ index.php?file=$1
    #matches everything else
    RewriteRule ^.*$ index.php
    

    Or you can do what is usually called bootstrapping which is where you use a single RewriteRule to redirect everything to a single php file like so:

    RewriteRule ^(.*)$ index.php
    

    And then you can just use php to determine what the different parts are. Inside php there is a built in server variable $_SERVER['REQUEST_URI'] that will give you the URI part of the url which is everything after the domain and first slash including any query string parameters. This is based on the URL that the user requested and not the one rewritten by apache. You can explode('/', $_SERVER['REQUEST_URI']) to get the individual parts and do whatever you want with them.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!