htaccess 操作合并两个不同的 RewriteRule 块
尝试合并两个不同的 .htaccess
块。
- 用于隐藏
*.php
扩展名:
RewriteRule ^([^\.]+)$ $1.php [NC,L]
- 用于重定向到特定 Web 是与 MySQL 行匹配的字符串:
RewriteRule ^([a-zA-Z0-9_-]+)$ friendly_url.php?friendly_url=$1
如果一个有效,则其他会被阻止,例如这种方式可以工作Friendly_url,但它不会隐藏 PHP 扩展名:
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ friendly_url.php?friendly_url=$1
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
我的 php 代码包含简单的查询:
$sql = "SELECT * FROM url WHERE friendly_url ='$friendly_url'";
$result = mysqli_query($connection, $sql);
if (!mysqli_num_rows($result) > 0) {
echo "page does not exist";
die();
} else {
echo "page exist";
}
我的最终目标是检查 file.php
是否存在,如果存在则重定向到 example.com/file
, 然后检查mysql中是否存在Friendly_url,如果存在 - 重定向到example.com/$Friendly_url
别的 echo "页面不存在";
两个 .htaccess 块都有效,但前提是删除其中一个。
Trying to merge two different .htaccess
blocks.
- for hiding
*.php
extension:
RewriteRule ^([^\.]+)$ $1.php [NC,L]
- for redirecting to specific web is string matched with MySQL row:
RewriteRule ^([a-zA-Z0-9_-]+)$ friendly_url.php?friendly_url=$1
If one works, other gets blocked, for example this way works friendly_url, but it doesn't hide PHP extension:
RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ friendly_url.php?friendly_url=$1
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
My php code contains simple query:
$sql = "SELECT * FROM url WHERE friendly_url ='$friendly_url'";
$result = mysqli_query($connection, $sql);
if (!mysqli_num_rows($result) > 0) {
echo "page does not exist";
die();
} else {
echo "page exist";
}
My end goal is to check if file.php
exist, if so redirect to example.com/file
,
then check if in mysql friendly_url exist, if so - redirect to example.com/$friendly_url
else
echo "page does not exist";
Both .htaccess blocks works, but only if one is deleted.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
颠倒这两个规则,不要检查请求是否没有映射到第二条规则中的文件,而是在重写之前检查相应的
.php
是否存在。例如,请尝试以下操作:
\w
简写字符类与[a-zA-Z0-9_]
相同。不需要在正则表达式字符类中反斜杠转义文字点。
上述规则现在所做的。但是,无法检查
.htaccess
中是否存在 MySQLFriendly_url。任何与模式^([\w 匹配的 URL -]+)$
(不作为.php
文件存在)将被重写为friend_url.php
仅与不匹配的 URL。模式并且不存在,然后将下降到404.Reverse the two rules and instead of checking that the request does not map to a file in the second rule, check that the corresponding
.php
exists before rewriting.For example, try the following instead:
The
\w
shorthand character class is the same as[a-zA-Z0-9_]
.There is no need to backslash-escape literal dots in the regex character class.
This is basically what the above rules now do. However, it's not possible to check if the MySQL friendly_url exists in
.htaccess
. Any URL that matches the pattern^([\w-]+)$
(that doesn't exist as a.php
file) will be rewritten tofriendly_url.php
. Only URLs that do not match that pattern and do not exist will then drop through to a 404.