简体   繁体   English

htaccess重写规则导致WordPress网站中出现404

[英]htaccess rewrite rule causing 404 in WordPress site

I am using a WordPress page with a custom page template that I am then sending GET data. 我正在使用具有自定义页面模板的WordPress页面,然后发送GET数据。 I want to rewrite http://example.com/blue/green to http://example.com/blue/?id=green 我想将http://example.com/blue/green重写为http://example.com/blue/?id=green

RewriteEngine On
RewriteBase /

RewriteRule ^blue/green/?$ /blue/?id=green [NC,L]

Taking this to the next step, I want to make green generic as below: 进行下一步,我要使绿色通用,如下所示:

RewriteEngine On
RewriteBase /

RewriteRule ^blue/([a-zA-Z0-9]+)/?$ /blue/?id=$1 [NC,L]

These rules are placed above the WordPress rules in the .htaccess file, but keep producing 404 errors. 这些规则位于.htaccess文件中的WordPress规则之上,但仍会产生404错误。

However, if I use a 301 redirect, it does work: 但是,如果我使用301重定向,则可以正常工作:

RewriteEngine On
RewriteBase /

RewriteRule ^blue/([a-zA-Z0-9]+)/?$ /blue/?id=$1 [R=301,NC,L]

Or if I put in the absolute URL it works too: 或者,如果我输入绝对URL,它也可以工作:

RewriteEngine On
RewriteBase /

RewriteRule ^blue/([a-zA-Z0-9]+)/?$ http://example.com/blue/?id=$1 [NC,L]

However, both of these cause the URL to change which I don't want, if possible. 但是,如果可能的话,这两者都会导致URL更改,而这是我不希望的。 So what is wrong with the first two htaccess statements? 那么前两个htaccess语句有什么问题呢?

Figured this out in the end. 最后想通了。 Have to use WordPress rewrite functions instead of htaccess directly. 必须直接使用WordPress重写功能而不是htaccess。 Here is my code in theme functions.php 这是我在主题functions.php中的代码

// Add query tags
add_filter( 'query_vars', 'stats_rewrite_tag' );
function stats_rewrite_tag( $query_vars )
{
    $query_vars[] = 'id';
    return $query_vars;
}

// Add to htaccess
function stats_rewrite_rule() {
    global $wp_rewrite;
    add_rewrite_rule(
        'blue(/([^/]+))?/?',
        'index.php?pagename=blue&slug=$matches[2]',
        'top'
    );
    $wp_rewrite->flush_rules( false );
}
add_action('init', 'stats_rewrite_rule');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM