将路由规则添加到 Wordpress HTACCESS 并保留 URL


Adding route rule to Wordpress HTACCESS and keep the URL

我想在我的.htaccess文件中添加一个不遵循Wordpress默认规则的规则。

一切都像这样:

1- /course/(:any)

必须重定向到:

2- /course/?slug=$1

但是我想将 URL 保留在 1 中,而不使用查询字符串。

我尝试的所有方法要么给我内部服务器错误,要么与规则不匹配。这就是我得到的,只是被忽略了(因为wordpress向我显示"找不到页面"消息)。生成的 URL 就像没有参数和更改 URL 的http://localhost/bethmoda/courses/?slug

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)/course/(.*)$ /bethmoda/course?slug=$2 [L]
RewriteBase /bethmoda/
RewriteRule ^index'.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /bethmoda/index.php [L]
</IfModule>
# END WordPress

我该怎么做?

您可以使用

以下规则:

RewriteEngine On
#Exclude /bethmoda/course/index.php
RewriteCond %{REQUEST_URI} !^/bethmoda/course/index'.php$ 
RewriteRule ^/?bethmoda/course/(.+)$ /bethmoda/course/?slug=$1 [NC,L]

重写Cond 对于避免第二次重写迭代时出现 RewriteLoop 错误非常重要,否则如果没有此条件,您将收到内部服务器错误。

以下是实现您想要的wordpress方法。

如果可能的话:用别的东西改"蛞蝓",让我们说"当然-蛞蝓"。

//Add query variable, so that wordpress identifies your custom query string
function add_custom_query_var( $qvars ) {
    $qvars[] = 'course-slug';
    return $qvars;
}
add_filter('query_vars', 'add_custom_query_var');

添加自定义重写规则

//Assumption: course is a page
add_filter( 'rewrite_rules_array', 'custom_rewrite_rules' );
function custom_rewrite_rules( $rewrite_rules )
{
  $pattern = "course/([^/]+)?$";
  $target  = "index.php?" . "name=course&course-slug='$matches[1]";
  // If course was a custom post type
  // $target  = "index.php?" . "post_type=course&course-slug='$matches[1]";
  // If course was a category
  // $target  = "index.php?" . "category_name=course&course-slug='$matches[1]";
  // If course was a tag
  // $target  = "index.php?" . "tag=course&course-slug='$matches[1]";
  $newRules[$pattern] = $target;
  return array_merge($newRules,$rewrite_rules);
}

齐平永久链接

Step 1: In the main menu find "Settings > Permalinks". 
Step 2: Scroll down if needed and click "Save Changes". 
Step 3: Rewrite rules and permalinks are flushed.