【问题标题】:.htaccess rewrite php to php file.htaccess 将 php 重写为 php 文件
【发布时间】:2014-05-22 00:31:25
【问题描述】:

我目前正在尝试编写重写规则。我想简化输入的 URL,以便它始终使用索引。输入 url 将是 www.example.com/home.php 并将被重写为 www.example.com/index.php?r=page/home

我写了这个.htaccess 文件:

RewriteEngine On
RewriteRule ^([^/]*)\.php$ /index.php?r=page/$1 [L]

不幸的是,这个配置给了我一个错误500。我可以理解这是因为如果我输入index.php,apache将不知道它是否必须使用index.php文件或使用重写的url index.php?r=page/index.

这种重写规则可以用apache来完成吗?如果是这样,我该如何解决我的错误 500?

编辑:请注意,如果我将扩展名 .php 更改为其他任何内容,例如 .html,RewriteRule 工作正常,如下所示:RewriteRule ^([^/]*)\.html$ /index.php?r=page/$1 [L]

【问题讨论】:

  • 错误 500 并不意味着您的 RewriteRule 错误或指向它不存在的页面。这意味着您的文件语法(我没有看到任何)或您的配置有错误。您的 .htaccess 文件中还有其他内容吗? mod_rewrite 是否安装正确?
  • 我尝试将重写规则更改为:“RewriteRule ^([^/]*)\.pr$ /index.php?r=page/$1 [L]”,当我尝试访问www.domain.com/home.pr...所以是“.php”导致错误。

标签: php apache .htaccess mod-rewrite url-rewriting


【解决方案1】:

你有两种可能。

第一个

RewriteEngine On
RewriteRule ^index\.php$ - [L]
RewriteRule ^([^/]+)\.php$ /index.php?r=page/$1 [L]

第二个

RewriteEngine On
RewriteCond %{THE_REQUEST} \ /([^/]+)\.php
RewriteRule ^.*$ /index.php?r=page/$1 [L]

【讨论】:

  • 很好的答案!正是我想要的。非常感谢。
  • 我用的是第一个,具体效果如何?破折号是什么意思?
  • 如果请求index.php,第一个不执行任何操作(破折号表示do nothing)。第二个使用THE_REQUEST:这样你可以区分内部重定向和原始请求。在这种情况下两者都是等价的
  • 太棒了!谢谢你的澄清
【解决方案2】:

你也可以试试这个:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?r=page/$1 [L]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-21
    • 2017-05-31
    • 2012-03-31
    • 1970-01-01
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    • 2013-10-08
    相关资源
    最近更新 更多