mod_rewrite:将 URL 中的“文件夹"转换为查询参数 [英] mod_rewrite: Convert 'Folders' in URL Into Query Parameters

查看:26
本文介绍了mod_rewrite:将 URL 中的“文件夹"转换为查询参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够采用如下网址:

I want to be able to take a URL like:

http://www.example.com/valOne/valTwo/valThree/valFour/valFive

并将其转换为:

http://www.example.com/index.php?one=valOne&two=valTwo&three=valThree&four=valFour&five=valFive

我的应用程序实际上只需要几个查询参数,因此正则表达式可以具有这五个硬编码,但是如果它可以在将附加文件夹"添加到 URL 时动态创建新的查询参数,那就太好了.此外,并非所有五个文件夹或 QP 都会一直存在,因此它必须能够适当地处理.

I really only need a few query parameters for my application so the Regular Expression could have these five hard coded, but it would be nice if it could dynamically create new query parameters as additional 'folders' are added to the URL. Additionally, not all five folders or QPs will always be present, so it must be able handle that appropriately.

推荐答案

这是一个满足您需求的 mod_rewrite 规则:

Here’s a mod_rewrite rule that meets your needs:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^/]*)/?([^/]*)/?([^/]*)/?([^/]*)/?([^/]*)/?$ index.php?one=$1&two=$2&three=$3&four=$4&five=$5

但是如果您改为使用 PHP 解析请求的 URI 路径肯定会更容易:

But it would be certainly easier if you parse the requested URI path with PHP instead:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule !^index\.php$ index.php

$_SERVER['REQUEST_URI_PATH'] = preg_replace('/\?.*/', '', $_SERVER['REQUEST_URI']);
$segments = explode('/', trim($_SERVER['REQUEST_URI_PATH'], '/'));
var_dump($segments);

这篇关于mod_rewrite:将 URL 中的“文件夹"转换为查询参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆