【问题标题】:Run PHP code from .htaccess?从.htaccess 运行PHP 代码?
【发布时间】:2009-06-24 14:12:59
【问题描述】:

假设我有一个重写,需要将 url 传递给 PHP 函数并检索一个值,以便告诉新的目的地应该是什么?有没有办法做到这一点?

谢谢。

更新:

到目前为止,谢谢大家..我仍然遇到问题,但我会向您展示我的代码:

.htaccess

#I got the file path by echoing DOCUMENT_ROOT and added the rest.
RewriteMap fixurl prg:/var/www/vhosts/mydomain.com/httpsdocs/domain_prototype/code_base/url_handler.php

RewriteEngine On
RewriteRule (.*) ${fixurl:$1} [PT]

PHP:

set_time_limit(0); # forever program!
$keyboard = fopen("php://stdin","r");
while (1) {
        $line = trim(fgets($keyboard));
        print "www.google.com\n";  # <-- just test to see if working.
}

但是我收到 500 内部服务器错误我不确定我的 .htaccess 或 PHP 中是否有错误?

【问题讨论】:

    标签: php apache .htaccess


    【解决方案1】:

    有一种东西叫做 RewriteMap。

    您可以调用一个可执行脚本,该脚本将返回要重写的 URL。

    查看这篇文章以获取更多信息和示例(在 Perl 中,但完全适用于任何其他语言):

    http://www.onlamp.com/pub/a/apache/2005/04/28/apacheckbk.html

    注意事项总结:

    • 必须运行读取 STDIN 循环(即,在收到 URL 后不要退出)
    • 必须打印要重写的 URL,并带有尾随换行符
    • 必须由运行 Apache 的用户读取和执行

    这是创建地图的方式

    RewriteMap fixurl prg:/usr/local/scripts/fixit.php
    

    现在我们可以在 RewriteRule 中使用它:

    RewriteEngine On
    RewriteRule (.*) ${fixurl:$1} 
    

    编辑:关于内部服务器错误。最可能的原因是 Gumbo 提到的,遗憾的是,RewriteMap 不能在 .htaccess 中使用。您可以在 .htaccess 的 RewriteRule 中使用它,但只能在服务器配置或虚拟主机配置中创建它。为了确定,请检查错误日志。

    因此,唯一的 PHP / .htaccess 唯一解决方案是将所有内容重写为某个 PHP 程序,该程序使用 Location 标头进行检查和重定向。比如:

    RewriteRule (.*) proxy.php?args=$1 [QSA]
    

    然后,在proxy.php中

    <?php
          $url = get_proper_destination($QUERY_STRING); #args will have the URI path, 
                                                        #and, via QSA you will have
                                                        #the original query string
          header("Location: $url");
    ?>
    

    【讨论】:

      【解决方案2】:

      是的;你需要一个RewriteMap,外部重写程序种类。

      【讨论】:

        【解决方案3】:

        我要做的是将 URL 传递给 PHP 页面,然后使用 PHP 标头选项进行最终重定向。

        header("Location: new-page.php");
        

        如果您不希望它重定向,您也可以包含您想要的页面。我发现这比使用 RewriteMap 灵活一点。

        希望这会有所帮助!

        【讨论】:

          【解决方案4】:

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-07-30
            • 2018-02-12
            • 1970-01-01
            • 2017-10-20
            • 1970-01-01
            • 2016-12-28
            • 2021-04-26
            • 1970-01-01
            相关资源
            最近更新 更多