【问题标题】:Rewrite .html to .php using mod_rewrite使用 mod_rewrite 将 .html 重写为 .php
【发布时间】:2012-06-13 11:37:48
【问题描述】:

我有一个重写条件和规则。

RewriteCond %{DOCUMENT_ROOT}$0 !-f
RewriteRule ^[^*]+$ index.php [L]

我需要在%{DOCUMENT_ROOT}$0 中将.html 替换为.php

原因是,我将我的网址重写为.html,但是当此文件检查现有文件时,由于%{DOCUMENT_ROOT}$0 正在寻找文件thefile.html 而失败,

我需要它来寻找thefile.php

【问题讨论】:

  • 请记住,这不会将 HTML 解释为 PHP。这似乎是人们会这么想的唯一真正原因。

标签: php html mod-rewrite


【解决方案1】:

解决了!

RewriteCond %{DOCUMENT_ROOT}$0 !-f
RewriteRule ^(.*).html$ $1.php [L]

RewriteCond %{DOCUMENT_ROOT}$0 !-f
RewriteRule ^[^*]+$ index.php [L]

我不得不使用它两次,首先,将所有 .html 重写为 .php,然后在请求 for.php 时,第二个条件开始发挥作用。

【讨论】:

    【解决方案2】:

    若要将 .html 扩展名重写为现有的同名 .php 文件,请尝试以下规则,而不是您已有的规则:

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)\.html$ $1.php?%{QUERY_STRING} [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^.*$ index.php [L]
    

    您刚刚将任何不存在的文件重写为 index.php

    【讨论】:

    • 谢谢,但是,如果该文件不存在,我会收到该代码的 404 错误。如果文件以 .php 存在(但请求将是 .html),我需要它转到文件,如果没有 index.php
    • 我在末尾添加了 2 行,因此它应该另外将不存在的文件重定向到 index.php
    • 对于那些寻找解释的人来说,第二个 RewriteRule 有效,因为在寻找新的 PHP 文件时,第二遍调用了 .htaccess。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多