【问题标题】:Removing .php extensions from output从输出中删除 .php 扩展名
【发布时间】:2014-11-18 22:36:36
【问题描述】:

我正在使用 Perch 开发一个小型 CMS 解决方案。它目前正在我本地开发机器上的 WampServer 上运行。

由于 Perch 不提供开箱即用的友好 URL,我想实现这一点,同时确保 /perch 目录保持不变。

到目前为止,我已经完成了重写部分,即对 /blog.php 的请求将 301 发送到 /blog,并且 /blog 将使用以下规则重写到 /blog.php:

Options +FollowSymLinks -MultiViews

RewriteEngine On

# Rewrites domiain.com/file to domain.com/file.php
RewriteCond %{REQUEST_URI} !^/perch
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php 

# Redirects domain.com/file.php to domain.com/file
RewriteCond %{REQUEST_URI} !^/perch
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteCond %{REQUEST_URI} ^(.+)\.php$
RewriteRule (.*)\.php$ /$1 [R=301,L]

但是,我仍然在 HTML 输出中保留了 .php 扩展名。我尝试将以下内容添加到我的 .htaccess 文件中:

AddOutputFilterByType SUBSTITUTE text/html
#Replace all .php extensions
Substitute s|.php||ni
#Original blog pattern /blog/post.php?s=2014-11-18-my-first-blog-post
Substitute s|blog/post\?s=(\w+)|blog/$1|i

但是,这适用于全局,即甚至适用于 /perch 文件夹中的链接。除了 /perch 文件夹之外,我找不到添加条件以将其应用于所有内容 - 有这样的方法吗?

我还查看了 ProxyPass/ProxyReversePass 文档,但是仅仅替换页面上的一些 HTML 似乎有点过头了。

任何帮助将不胜感激。

亲切的问候, 点开发

【问题讨论】:

    标签: apache .htaccess mod-rewrite wampserver perch


    【解决方案1】:

    您是在谈论来自 www.grabaperch.com 的 Perch CMS 吗?

    一切都在这里:http://docs.grabaperch.com/video/v/simple-url-rewriting/

    但是,我仍然在 HTML 输出中留下了 .php 扩展名

    .htaccess / mod_rewrite 对您的 HTML 输出没有任何作用。

    将 RewriteRules 视为将邮件 (URL) 投递到目标邮箱(实际文件)的邮递员。

    您所做的是“手动”省略标记中的 .php 扩展名(HTML 输出):

    • perch_pages_navigation()中,需要将hide-extensions设置为true
    • 您手动添加的 URL:只需编写不带 .php 的 URL

    现在您需要指示邮递员将这些地址路由到 .php 文件。这就是这些 RewriteRules 的用途。所以 .htaccess 不会删除 .php 后缀 - 相反,它会添加它。

    这是 Perch(或任何“删除 .php”用例)+ Perch 博客的基本 .htaccess(进入您的 public_html 目录)。我已经添加了一些解释:

    # make sure the address we received (e.g. /mypage) is not an existing file      
    RewriteCond %{REQUEST_FILENAME} !-f
    #  make sure it's not an existing directory either
    RewriteCond %{REQUEST_FILENAME} !-d
    # make sure there IS an existing .php file corresponding to it
    RewriteCond %{REQUEST_FILENAME}.php -f
    # if the address starts with "blog/", pick what comes afterwards, put it into the GET Parameter and quit (that's the [L]) 
    RewriteRule ^blog/([a-zA-Z0-9-/]+)$ /blog/post.php?s=$1 [L]
    # if the first conditions are ok, but it wasn't a blog post (else we would have quit), just append .php to it. Ah, and keep other get params (that's the QSA=Query String Append). 
    RewriteRule ^(.+)$ $1.php [L,QSA]
    

    对于更精细的可能性,您可以例如从这里开始:https://github.com/PerchCMS/perchdemo-swift/blob/master/public_html/.htaccess

    这对 /perch/ 中 CMS 的功能完全没有影响。

    【讨论】:

      最近更新 更多