使用mod_rewrite模拟多个子目录
我的 .htaccess 文件目前看起来像这样:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule /?([A-Za-z0-9-]+)/?$ index.php?page=$1 [QSA,L]
对于像 http://site.com/aaaaa 这样的网址效果很好,但是对于像 http://site.com/aaaa/bbb 这样的 URL,$_GET['page'] 变量将仅包含 bbb 而不是 aaaaa/bbb。
有没有办法获取页面变量中的所有子目录?
My .htaccess file currently looks like this:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule /?([A-Za-z0-9-]+)/?$ index.php?page=$1 [QSA,L]
It works fine for urls like http://site.com/aaaaa but for urls like http://site.com/aaaa/bbb the $_GET['page'] variable will only contain bbb rather than aaaaa/bbb.
Is there a way to get all of the sub-directories in the page variable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您使用这些字符范围有什么原因吗?
为什么不使用:
使用这样的东西也有危险,你可能会错过“page”GET 变量。我不确定哪个优先,但其中任何一个都是不良行为。
我看到的这种行为的示例不会将路径作为 GET 参数传递,而是使用 php 从
$_SERVER['REQUEST_URI')
中提取它Is there any reason you are using those ranges of characters?
Why not use:
Also the danger is using something like this is you could miss the "page" GET variable. I'm not sure which gets precedence, but either is bad behaviour.
Examples I've seen of this behaviour don't pass the path through as a GET parameter, but instead use php to extract it from
$_SERVER['REQUEST_URI')
如果您只想在每个 路径段,试试这个:
顺便说一句:您应该选择一种拼写,带或不带尾部斜杠,如果是另一种形式则重定向。
If you only want to allow the characters
[A-Za-z0-9-]
in each path segments, try this:By the way: You should choose one spelling, with or without trailing slash, and redirect if it’s the other form.
我建议将
/
添加到最后一行中接受的字符列表中:/?([A-Za-z0-9/-]+)/?$
。I suggest adding
/
to the list of accepted characters in your last line:/?([A-Za-z0-9/-]+)/?$
.为什么不直接捕获一切?
像这样,我想:
有了这个(考虑到我的脚本位于
temp
文件夹中),http://tests/temp/blah
和http: //tests/temp/blah/glop
重定向到 temp.php
,其中$_GET['page']
包含 'blah' 或'blah/glop'
。这通常是使用 Zend Framework 完成的,例如(请参阅此处供参考)。
Why not just capture everything ?
Like this, I suppose :
With this (considering my script is in the
temp
folder), bothhttp://tests/temp/blah
andhttp://tests/temp/blah/glop
get redirected to temp.php
, with$_GET['page']
containg 'blah' or'blah/glop'
.That's generally what's done with Zend Framework, for instance (see here for a reference).
在这一行上:
您错过了匹配整个字符串的
^
。另外,在字符串中,您希望匹配 URL 中的/
。所以它应该是:错过
^
会让你得到最后一个非贪婪的匹配。On this line:
You missed out the
^
to match the entire string. Also, in your string you want to match/
in the URL. So it should have been:Missing out
^
will get you the last ungreedy match.