【问题标题】:mod_rewrite conflict, two strings, and a file including othersmod_rewrite 冲突、两个字符串和一个包含其他字符串的文件
【发布时间】:2013-06-28 05:56:53
【问题描述】:

首先解释一下 index.php 在我的站点中是如何工作的。

首先,index.php 具有过滤 GET 名称(如果不为空)的功能,并且存在我的页面的名称(我定义的),例如博客、照片、模式、关于和联系人,因此请包含具有相同名称的文件请求名称 GET

我的 htacess 适用于单页,例如模式、关于、联系方式,但现在我想添加“子类别”,例如 blog/hello-world。

blog.php 的工作方式与索引相同,它包含来自 GET 变量(post)的同名文件。

换句话说,让我们看看实际情况。

index.php?page=modalities -> /modalities
index.php?page=blog&post=nameofpost -> 我可以正确看到 但是当使用 htaccess 时与第一条规则有冲突,因为它将博客作为单个文件进行分析,并且没有空间到另一个 GET 变量

我想将 index.php?page=blog&post=nameofpost 重写为 /blog/nameofpost 而不会与重写的第一条规则发生冲突。

重写规则 (.*) index.php?pg=$1 [L]

如果我在重写规则的过程中使用更多字符串,我无法将其用于我的单个页面,例如联系人 (index.php?pg=contact /contact),它会给我一个 404 错误。

我的 index.php(结构)

$url =  addslashes($_GET["pg"]);

    if(isset($url) && ($url === "photos" || $url === "time" || $url === "modalities" || $url === "contact" || $url === "blog" || $url === "about")){

        include "page/{$url}.php";

        return $lock = true;
        }elseif($url === "" || $url === "home" || !isset($url) || (empty($url) || trim($url)==='')){

            include "home.php";


            }else{


                echo "Error 404";

                }

.htaccess 文件:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (.*) index.php?pg=$1 [L]
ErrorDocument 404 /404
ErrorDocument 403 /404
ErrorDocument 404 /404
Options -Indexes 
IndexIgnore *

我知道 .htaccess 文件没有配置,因为我找不到解决方案,同时使用两种类型的 url。

提前感谢您的关注。

【问题讨论】:

    标签: php algorithm mod-rewrite logic structure


    【解决方案1】:

    以下 RewriteRule 将允许您有两个级别,将路径的第一部分重写为 pg=,将路径的其余部分重写为 post=

    RewriteRule ^([^/]+)/([^/]+)/?$ index.php?pg=$1&post=$2 [L]
    

    为确保这不会干扰您现有的规则,您应该更改现有的 RewriteRule 以匹配任何不是路径分隔符 (/) 的内容:

    RewriteRule ^([^/]*)/?$ index.php?pg=$1 [L]
    

    【讨论】:

    • 谢谢,但不起作用,当我在字符串末尾使用斜杠时,例如 mysite.com/about/ 它显示内容(PHP)但它添加了我的 html 的双路径,比如 style/style/site.css img/img/image01.jpg 它只有在我同时使用第一条或第二条规则时才有效,就像你告诉两个级别的重写一样。 RewriteRule ([^/]*) index.php?pg=$1 [L] 用于单页,如模式、关于、联系... RewriteRule (.*)/(.*) index.php?pg=$1&post= $2 [L] 以及带有子页面的页面,例如博客、新闻等...
    • 我无法在周末编辑这个,所以我现在更新了答案——如果你把这两个规则都放在你的 .htaccess 文件中,它应该(!!)工作。它也应该处理斜杠。
    • 很高兴您的关注,我们将进行测试。
    猜你喜欢
    • 2019-01-04
    • 2013-11-26
    • 2013-04-08
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 2012-11-21
    相关资源
    最近更新 更多