I'm trying to allow url-redirection (from /dl urls) only if user is logged-in to wordpress site. Otherwise don't allow. However it went "page not found" when i click these urls with or without logging in.

I've used this .htaccess code on public-html level:

RewriteEngine On
RewriteCond %{HTTP_COOKIE} ^.*wordpress_logged_in.*$ [NC]
RewriteRule ^dl/?$ https://external.com/directdownload- [L,R=301]

I expect to allow logged-in users to redirect to https://external.com/directdownload- links and don't allow redirection (and redirect them to login page) if they are not logged-in to wordpress. However when i click the links which are like https://www.example.com/dl/23434234/link.html both logged-in and not logged-in goes to "page not found". How to fix?

also tried below code and get the same file code when i click :'''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 

    //user has valid WP login session
    header('Location: {location of perl script}');
    //user is not logged in
    header('Location: {location to boot them to}');
exit; //just because

How can i change above code to make it useful?

1 Answer 1


An htaccess rule is evaluated before WP is called to get page content. So there is no variable you could use in an htaccess rule to check if a user is logged in.

Instead, I'd add to your functions.php file code that would check the is_user_logged_in() result. If not logged in, then use wp_redirect() to redirect to a login page. The die() is important after the wp_redirect so that the redirect will work properly.

Code would look something like this (not tested):

function check_user_logged_in() {
if (! is_user_logged_in()) {
   // not logged in, so redirect them
add_filter("init", "check_user_logged_in"); // fires the function on WP init

Of course, this should be placed in your Child Theme's functions.php file.

Added 20 Jul 2020

Corrected the code fragment to be is_user_logged_in - which I did speify correctly in the non-code portion of the answer. Thanks to @Frits for his eagle eye. (I did say it was untested code, so maybe that's my excuse....)

  • Correct me if I am wrong - but is the function not supposed to be is_user_logged_in() instead of user_logged_in()?
    – Frits
    Commented Jul 20, 2020 at 9:06
  • Well, I did use the correct function name in the non-code section. I blame my keyboard. Fixed the code. Thanks @Frits Commented Jul 20, 2020 at 17:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.