How to require wordpress login to view a subdirectory within the wordpress site?

I have my WordPress site at xroads.com

Inside, there is a folder called “_warehouse” which contains a php CRUD app

Read More

Is it possible to require the same login page I use for the WordPress site to view the _warehouse directory?

Thanks in advance!

enter image description here

Related posts

2 comments

  1. If the user already has an account in WordPress:

    Redirect the user to the login form. Use wp_login_url with the $redirect parameter to set where they go after logging in:

    $loginUrl = wp_login_url( home_url('_warehouse') );
    

    https://codex.wordpress.org/Function_Reference/wp_login_url

    Then use the wp_login action to manually authenticate the user in your application:

    add_action('wp_login', function($username, $user) {
        // Log user into external application
    }, 10, 2);
    

    https://codex.wordpress.org/Plugin_API/Action_Reference/wp_login

    Actually setting the user as “logged in” is going to depend on how your external application is setup. It could be as simple as setting a session variable and then checking if that is set in your warehouse app.

  2. Here is one possible solution (use at your own risk).

    Create a .htaccess file in the _warehouse directory with the following content:

    RewriteEngine On
    
    RewriteCond %{REQUEST_FILENAME} -f
    RewriteRule ^.*$ wplogin.php [NC,L]
    

    This will redirect all requests for files that exist in _warehouse and any subdirectories to _warehouse/wplogin.php

    Create _warehouse/wplogin.php with the following content:

    <?php
    
    // Edit this path to include wp-load.php from your WordPress directory
    require_once '../wp-load.php';
    
    if (!is_user_logged_in()) {
        // if user is not logged in, set redirect URI, show WP login
        $_REQUEST['redirect_to'] = $_SERVER['REQUEST_URI'];
        require_once '../wordpress/wp-login.php';
        exit;
    } else {
        // user is logged into wordpress - show the requsted file.
        require_once $_SERVER['DOCUMENT_ROOT'] . $_SERVER['REQUEST_URI'];
    }
    

    Lastly, and very important, add this to your wp-config.php file:

    define('COOKIEPATH', '/');
    

    This is because WordPress will set cookies with a path specified. This would prevent the login cookies from being recognized in _warehouse.

    And as I said, use at your own risk. It is not perfect but is probably the quickest way to achieve what you want and will handle many cases.

    Note: it doesn’t deal with directories with no index. If Apache Options +Indexes is on, someone may be able to see directory listings in _warehouse but if they try to access one it will show the login page.

Comments are closed.