add_rewrite_rule()
是 WordPress 中用于添加自定义重写规则的一个函数,它允许开发者创建更加友好的 URL 结构。而 RewriteCond
则是在 .htaccess
文件中使用的 Apache 服务器的重写条件指令,它用于指定在应用重写规则之前需要满足的条件。
add_rewrite_rule():
RewriteCond:
RewriteCond
是 Apache 的 mod_rewrite 模块中的一个指令,用于设置重写规则的条件。类型:
应用场景:
example.com/?p=123
重写为 example.com/my-first-post/
。example.com/shop/product?id=456
重写为 example.com/shop/my-product/
。假设你想将所有形如 example.com/year/month/day/post-name/
的 URL 重写到 WordPress 的默认查询结构,可以使用以下代码:
function custom_rewrite_rules() {
add_rewrite_rule(
'^([0-9]{4})/([0-9]{2})/([0-9]{2})/([^/]+)/?$',
'index.php?year=$matches[1]&monthnum=$matches[2]&day=$matches[3]&name=$matches[4]',
'top'
);
}
add_action('init', 'custom_rewrite_rules');
在 .htaccess
文件中,你可能需要添加 RewriteCond
来限制规则的应用,例如:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
问题: 添加了重写规则后,某些页面无法访问或出现 404 错误。
原因:
解决方法:
RewriteEngine
已经开启。.htaccess
文件中的规则干扰了你的规则。通过以上步骤,通常可以解决大多数与 WordPress 重写规则相关的问题。
领取专属 10元无门槛券
手把手带您无忧上云