优化 .htaccess 中的漂亮 URL

发布于 2024-08-17 08:58:19 字数 699 浏览 8 评论 0原文

这是我使用的代码,

<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 技术交流群。

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

发布评论

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

评论(3

遇见了你 2024-08-24 08:58:19

第二部分 ($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'

眼泪淡了忧伤 2024-08-24 08:58:19

非常简单的修改:

 ^([^/]+)/?([^/]*)

Very simple modification:

 ^([^/]+)/?([^/]*)
数理化全能战士 2024-08-24 08:58:19

规则中的问号和第二个加号导致它以这种方式分割。您应该删除问号,因为您已经需要第二组中至少有一个字符。

编辑:
在这种情况下,请使用:

RewriteRule ^([^/]+)(/([^/]+))?$ index.php?user=$1&do=$3 [L]

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:

RewriteRule ^([^/]+)(/([^/]+))?$ index.php?user=$1&do=$3 [L]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文