使用 n 个参数的 Apache URL 重写

发布于 2024-08-21 12:51:31 字数 437 浏览 4 评论 0原文

我正在做一些 URL 重写,我可以通过以下方式完成我需要做的事情:

RewriteRule ^([^/]*)/([^/]*)$ index.php?arg1=$1&arg2=$2 [L,QSA]
RewriteRule ^([^/]*)$ index.php?arg1=$1 [L,QSA]

你明白了我在这里想做的事情,我基本上想获取完整的 url 并将其解析为单独的参数。所以 /blah/test/asdf/hi 将以 arg1=blah、arg2=test 等形式出现。

现在,如果我想将其扩展为 4 或 5 个参数,我想知道是否有一种更简洁的方式来呈现它比出去 ?arg1=$1&arg2=$2&arg3=$3 等等。我见过人们以编程方式执行此操作(只需用斜杠获取整个字符串并在代码中解析它),但我很好奇是否有一种用 apache 来做的方法。

I'm doing some URL rewriting and I can accomplish what I need to do with the following:

RewriteRule ^([^/]*)/([^/]*)$ index.php?arg1=$1&arg2=$2 [L,QSA]
RewriteRule ^([^/]*)$ index.php?arg1=$1 [L,QSA]

You get what I'm trying to do here, I basically want to take the full url and parse it into individual arguments. So /blah/test/asdf/hi would come in as arg1=blah, arg2=test, etc.

Now, if I want to expand this to 4 or 5 arguments, I'm wondering if there's a cleaner way to present it rather than going out with ?arg1=$1&arg2=$2&arg3=$3 etc. etc. I've seen people do this programatically (just take whole string with slashes and parse it in code) but I was curious if there was a way to do it with apache.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谁与争疯 2024-08-28 12:51:31

您可以使用 PHP 来执行此操作:

$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

$pathSegments = array_map('rawurldecode', explode('/', substr($_SERVER['REQUEST_URI_PATH'], 1)));

第一行仅从请求 URL 获取 URL 路径。另一行将删除前导斜杠 (substr),分成段 (explode) 并解码每个段 (array_maprawrurldecode)。

现在您只需将所有请求传递到您的 index.php

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

附加条件将排除可以映射到现有文件的请求。

You can use PHP to do that:

$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

$pathSegments = array_map('rawurldecode', explode('/', substr($_SERVER['REQUEST_URI_PATH'], 1)));

The first line is to get just the URL path from the request URL. The other line will remove the leading slash (substr), split into the segments (explode) and decode each segment (array_map with rawrurldecode).

Now you just need to pass all request to your index.php:

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

The additional condition will exclude requests that can be mapped to existing files.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文