【问题标题】:htaccess rewrite specific slug to specific pagehtaccess 将特定 slug 重写到特定页面
【发布时间】:2013-07-02 19:29:09
【问题描述】:

我目前正在构建一个简单的 CMS,我想将特定的 slug(如 /setup 和 /admin)重写到它们各自的页面,同时允许 htaccess 重写所有其余请求到我的服务页面。

这是我现在的 .htaccess 中的内容:

Options +FollowSymlinks -MultiViews
RewriteEngine on
#RewriteBase /

# Rewrite the setup slug to the setup page
RewriteCond %{REQUEST_URI} ^/setup$
RewriteRule ^/setup$ /setup.php [L,R=301]

# Rewrite all other URL's to the keyhole that translates them
RewriteRule ^(.*)$ keyhole.php?slug=$1 [L,QSA]

目前,重定向适用于所有其他 URL。它捕获它们中的每一个,然后将它们发送到 keyhole.php。但是,当我尝试访问 http://localhost/basic-cms/setup 时,它会将我重定向到 http://localhost/var/www/basic-cms/setup.php

另外,我认为这很奇怪,如果我尝试转到 http://localhost/basic-cms/setup.php,那么它会将我带到 http://localhost/setup.php

此外,当我取消注释 RewriteBase 时,我仍然遇到同样的问题,然后它破坏了我的其他包罗万象的重写行。

编辑:

我从给出的答案中获取了信息,并有一个新的 .htaccess 文件:

Options +FollowSymlinks -MultiViews
RewriteEngine on
RewriteBase /

# Rewrite the setup slug to the setup page
RewriteCond %{REQUEST_URI} ^setup$
RewriteRule ^setup$ setup.php [L]

# Rewrite all URL's to the keyhole that translates them
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ basic-cms/keyhole.php?slug=$1 [L,QSA]

然而,虽然我不再从 setup 重定向中得到奇怪的重定向,但似乎仍然没有将 setup 带到 setup.php。它表现得好像它已经跳过了检查 ^setup$ 的 RewriteCond。我想知道这是否与我新建立的 RewriteBase 有关...

最终编辑:

好的,在咀嚼了一段时间之后,我发现了我哪里出错了。这是我搞砸的条件,因为我已将 RewriteBase 添加到等式中。因此,为了记录,这是允许我将所有 slug 重定向到 keyhole.php 的工作 .htaccess,除了 setup slug,它将直接转到 setup.php:

Options +FollowSymlinks -MultiViews
RewriteEngine on
RewriteBase /

# Rewrite the setup slug to the setup page
RewriteCond %{REQUEST_URI} ^/basic-cms/setup$
RewriteRule ^(.*)$ basic-cms/setup.php [L]

# Rewrite all URL's to the keyhole that translates them
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ basic-cms/keyhole.php?slug=$1 [L,QSA]

显然,由于我是在本地 Apache 实例上构建的,而且我还没有设置虚拟主机,所以当我将这个 htaccess 文件移动到一个真实的 URL 时,它会被修剪一点,所以它不包含路径的“basic-cms”部分,因为该目录将不可避免地位于实时 Web 服务器上的根目录中。

【问题讨论】:

    标签: .htaccess mod-rewrite url-rewriting


    【解决方案1】:

    您想要的是内部重定向,但是根据您的规则,您 R=301 将其删除并仅留下 [L]

    您可能还想在您的 keyhole.php 规则中添加以下条件:

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    

    为了避免将现有页面或目录重定向到自身,但这取决于您将如何使用 CMS。

    来自 CMS,WordPress 基地 .htaccess 请注意他们如何使用上述内容:

    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    

    【讨论】:

    • 这很有帮助,谢谢!现在似乎它现在完全跳过了 ^setup$ 的 RewriteCond。我认为这可能只是我提出条件的方式。如果我在您有机会回复之前弄清楚了,我会添加一个编辑来描述我的错误,并将其标记为答案。
    • 找到了。我刚刚搞砸了我的状况。现在一切都很好。感谢您的帮助!
    • @SamHuckaby 很高兴你弄清楚了,我的帖子对你有帮助
    猜你喜欢
    • 1970-01-01
    • 2017-08-16
    • 2018-06-15
    • 1970-01-01
    • 2016-03-31
    • 2018-04-22
    • 2017-07-18
    • 2019-01-15
    • 1970-01-01
    相关资源
    最近更新 更多