如何只允许已登录的wordpress用户下载URL重定向?

时间:2019-05-17 16:29:46

标签: php wordpress .htaccess session redirect

我正在设置外部直接下载链接的下载重定向,以便即使在已登录成员的情况下也不会在wordpress中显示它们,并且如果它们不在wp之外,也不会使他们访问重定向的下载链接。所以基本上

直接下载链接(在我可以控制的外部站点上,基于Perl的脚本上)如下: external.com/directdownload-34j5hjhj54/file1.html 要么 external.com/directdownload-87897kk78/file2.html 要么 .....等 我将用example.com/dl/34j5hjhj54/file21.html

替换所有这些链接

为此,我首先将“ / dl /”重定向到htaccess中的download.php:

第二,将以下代码添加到download.php:

1)在.htaccess上:

RewriteEngine On

RewriteRule ^dl$ /download.php [L]

2)on download.php

//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: {https://external.com/directdownload-}');

}else{

    //user is not logged in

    header('Location: {/wp-login.php}');

}

exit; //just because

或 这段代码在download.php上:

require('../wp-load.php');  // modify to reflect where your PHP file is in relation to Wordpress
$roles = wp_get_current_user()->roles;  // get current users role

if (!in_array('alloweduserrole',$roles)) {  // modify to match your roles that are allowed to download

    header('Location: http://www.ourwebsite.com/');
    exit;

}  // end of if user does not have the proper role

我期望登录的成员重定向https://external.com/directdownload-链接,非登录的成员重定向wp-login.php,但是什么也没有发生,实际上它们都进入了“找不到页面”。怎么修?我应该更改哪些代码?

1 个答案:

答案 0 :(得分:0)

将此添加到您的.htaccess顶部

RewriteRule ^dl(.*)$ /download.php$1 [L]

这将是download.php内容:

<?php
define('WP_USE_THEMES', false);
require_once './wp-load.php';
if ( !function_exists( 'is_user_logged_in' ) ) {
    require_once './wp-includes/pluggable.php';
}

if( is_user_logged_in() ){

    //user is logged in
    $location = end(explode('dl/', $_SERVER['REQUEST_URI']));
    $location = ltrim($location, '/');
    wp_redirect( 'https://external.com/directdownload-' . $location );
    exit;

}else{

    //user is not logged in
    wp_redirect( home_url('/wp-login.php') );
    exit;

}

exit; //just because
?>

这是经过测试的代码,.htaccess将在/ dl /上重写对download.php的请求,后者将在/ dl /之后的url中提取任何内容,并在检查用户是否登录后将其添加到最终重定向链接中如果未登录,它将重定向到登录页面。

相关问题