从URL上删除查询字符串-重定向插件

时间:2016-11-03 作者:Nate Beers

当我重定向URL时,我试图从URL中删除查询字符串,但它保留了它们。我不能正确地使用正则表达式。

此外,我有多个重定向到不同URL的模板,所以我不能只使用.* 之后howto.php

.htaccess 在这种情况下不是一个选项,所以我必须在重定向插件中找出如何做到这一点

我想要/templates/howto.php?page=template-business-plan

转到

/business-plan

但我一直在/business-plan?page=template-business-plan

2 个回复
SO网友:socki03

我也使用这个插件,所以我想我应该深入研究代码,看看是否能找到答案。

有两个操作可用于此操作,这两个操作可能会首先使用redirection\\u,最后使用redirection\\u

两者都有两个参数:$url和$this(这是重定向插件的wordpress模块)

以下是\\modules\\wordpress中模块init()的代码片段。php

public function init() {
    $url = $_SERVER[\'REQUEST_URI\'];

    // Make sure we don\'t try and redirect something essential
    if ( ! $this->protected_url( $url ) && $this->matched === false ) {
        do_action( \'redirection_first\', $url, $this );

        $redirects = Red_Item::get_for_url( $url, \'wp\' );

        foreach ( (array) $redirects as $item ) {
            if ( $item->matches( $url ) ) {
                $this->matched = $item;
                break;
            }
        }

        do_action( \'redirection_last\', $url, $this );
    }
}
所以,$url是您请求的url,在redirection\\u last,$this->matched中有您的重定向url。我将从redirection\\u start开始,您可以运行如下操作:

function redirection_strip_query_string( $url = \'\', $this ) {

    if ( strpos( $url, \'?page=\' ) !== false ) {

        $url = preg_replace(\'/\\?.*/\', \'\', $url);

    }

}

add_action( \'redirection_first\', \'redirection_strip_query_string\' );
两个注意事项:

我尚未测试此代码simple URL preg_replace

SO网友:Vladan

我通过对插件代码进行轻微更改,添加了两个过滤器挂钩,解决了这个问题。希望作者将这些钩子-2非破坏性的线条结合起来,因为它们允许我们对插件行为进行更多的定制。此处详细说明:https://github.com/johngodley/redirection/issues/180

更新:我的这个“建议”是在插件本身的上游合并的,所以没有必要修改任何东西:我们现在有redirection_url_targetredirection_url_source 筛选,以便自定义代码可以出于特殊目的操纵源和目标重定向。现在在那里

相关推荐

Redirect htaccess

我需要帮助重定向我的页面。例如,我有网站https://example.com. 我需要将内容从https://example.com 到https://example.com/blog. 这不是问题,我通过更改主页URL来做到这一点。这很有效。但现在我需要添加来自旧的重定向https://example.com 到https://xmpl.com.我想用。htaccess,但这不起作用。你们能帮帮我吗?以下是我对此的一些尝试,但两者都不起作用。RewriteEngine On RewriteRu