优化 .htaccess 中的漂亮 URL
这是我使用的代码,
<IfModule mod_rewrite.c>
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^([^/]+)/?([^/]+) index.php?user=$1&do=$2 [L]
</IfModule>
如果我给它 abcd/1234
,它将首先捕获 abcd
然后捕获 1234
作为第二个变量。但是,如果 url 为 abcd/
或 abcd
,则第一个捕获保持不变,但第二个捕获变为 d
。这不会对 php 代码本身造成任何问题,但如果一开始就不捕获它,效率会更高。
需要澄清的是,index.php 页面不需要第一次或第二次捕获。但如果它们存在的话,将会改变它的目的。
任何有关正则表达式代码的帮助将不胜感激,如果有任何办法可以进一步改进它或更有效地编写它,我将非常感激知道!
非常感谢你:)
我使用这个工具 http://gskinner.com/RegExr/ 来检查这一点。
This is the code I use,
<IfModule mod_rewrite.c>
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^([^/]+)/?([^/]+) index.php?user=$1&do=$2 [L]
</IfModule>
if i give it abcd/1234
it will capture abcd
first then 1234
as the second variable. But if the url was abcd/
or abcd
the first capture stays the same, yet the second capture becomes d
. This would cause no problem in the php code itself, yet it would be more efficient if it was not captured in the first place.
oh to clarify, neither the first or second capture are required for the index.php page. But will change its purpose if they exist.
any help with the regex code would be appreciated, and if there are anyways to improve it more or write it more efficiently i would be very grateful to know!
Thank You very Much : )
i use this tool http://gskinner.com/RegExr/ to check this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
第二部分 ($2) 是非可选的,因为您编写了
[^/]+
。我会将整个内容替换为^([^/]+)(?:/([^/]+))?
,这会导致以下结果:abcd -> $1='abcd' $2=''
abcd/ -> $1='abcd' $2=''
abcd/某事 -> $1='abcd' $2='某事'
The second part ($2) is non-optional because you wrote
[^/]+
. I would replace the whole thing by^([^/]+)(?:/([^/]+))?
which leads to the following results:abcd -> $1='abcd' $2=''
abcd/ -> $1='abcd' $2=''
abcd/something -> $1='abcd' $2='something'
非常简单的修改:
Very simple modification:
规则中的问号和第二个加号导致它以这种方式分割。您应该删除问号,因为您已经需要第二组中至少有一个字符。
编辑:
在这种情况下,请使用:
The question mark in the rule along with the second plus sign is causing it to be split this way. You should remove the question mark since you already require at least one character in the second group.
Edit:
In that case, use this: