我正在尝试仅当用户登录到wordpress站点时才允许url重定向(从/dl url)。否则不允许。然而,无论登录与否,当我单击这些URL时,都会出现“找不到页面”的情况。
我用过这个。公共html级别的htaccess代码:
RewriteEngine On
RewriteCond %{HTTP_COOKIE} ^.*wordpress_logged_in.*$ [NC]
RewriteRule ^dl/?$ https://external.com/directdownload- [L,R=301]
我希望允许登录用户重定向到
https://external.com/directdownload- 链接,如果未登录到wordpress,则不允许重定向(并将其重定向到登录页)。然而,当我点击如下链接时
https://www.example.com/dl/23434234/link.html 登录和未登录都会转到“未找到页面”。如何修复?
还尝试了以下代码,并在单击“”时获得了相同的文件代码www.example.com/download.php/2n234n23/file.html\'\'\' : \'\'\'//load WP without theme support or hooks etc. define(\'WP_USE_THEMES\', false);\'\'\'
//load WP without theme support or hooks etc.
define(\'WP_USE_THEMES\', false);
require(\'./wp-load.php\'); //location of this file may be different
if(get_current_user_id()){
//user has valid WP login session
header(\'Location: {location of perl script}\');
}else{
//user is not logged in
header(\'Location: {location to boot them to}\');
}
exit; //just because
如何更改上述代码以使其有用?
SO网友:Rick Hellewell
评估htaccess规则before 调用WP以获取页面内容。因此,在htaccess规则中没有可以用来检查用户是否登录的变量。
相反,我会添加到您的函数中。php文件代码,用于检查is_user_logged_in() 后果如果未登录,则使用wp_redirect() 重定向到登录页面。这个die() 在wp\\u重定向之后非常重要,以便重定向正常工作。
代码如下所示(未测试):
function check_user_logged_in() {
if (! is_user_logged_in()) {
// not logged in, so redirect them
wp_redirect("https://www.example.com/login-page");
die();
}
return;}
add_filter("init", "check_user_logged_in"); // fires the function on WP init
当然,这应该放在子主题的函数中。php文件。
Added 20 Jul 2020
已将代码片段更正为
is_user_logged_in - 我在答案的非代码部分正确地说明了这一点。感谢@Frits的鹰眼。(我确实说过这是未经测试的代码,所以这可能是我的借口……)