【问题标题】:Adding route rule to Wordpress HTACCESS and keep the URL将路由规则添加到 Wordpress HTACCESS 并保留 URL
【发布时间】:2016-02-03 15:13:50
【问题描述】:

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

一切都是这样的:

1- /course/(:any)

必须重定向到这个:

2- /course/?slug=$1

但我想将 URL 保持在 1 中,不带查询字符串。

我尝试的一切要么给我一个内部服务器错误,要么不符合规则。这就是我得到的,只是被忽略了(因为 wordpress 向我显示了“找不到页面”消息)。生成的 URL 就像 http://localhost/bethmoda/courses/?slug 没有参数并更改 URL

# 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

我该怎么做?

【问题讨论】:

  • 抱歉,我没有复制我的 htaccess 内容。现在正在编辑

标签: php wordpress apache .htaccess mod-rewrite


【解决方案1】:

您可以使用以下规则:

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

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

【讨论】:

  • 我现在收到 apache 404 错误。为什么/index\.php$ 部分很重要?
  • index.php 是您的课程目录的目录处理程序。 /course?slug=foo 在第二次迭代中更改为 /course/index.php?slug=foo 并匹配模式 /course/(.*)$ 导致无限循环错误。
  • 课程不是我项目中的目录。这是一个响应 /bethmoda/course 的 wordpress 页面
  • 在这种情况下,我认为这不应该使用mod_rewrite 来完成。不是 WordPress 用户,但我相信您可以使用 URI 段来发挥自己的优势,并且不需要 slug 参数...
【解决方案2】:

以下是实现你想要的wordpress方式。

如果可能:将“slug”换成别的东西,让我们说“course-slug”。

//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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-11-03
    • 2018-02-20
    • 2015-02-06
    • 2015-01-25
    • 2023-03-03
    相关资源
    最近更新 更多