Search code examples
phpapache.htaccessmodx.htpasswd

How do I password protect resources in a ModX Website using htaccess and htpasswd?


We are trying to protect a couple of different resources in our ModX installation. The current .htaccess code is as follows (not including all of the ModX stuff)

AuthName "Dialog prompt"
AuthType Basic
AuthUserFile /var/www/vhosts/mywebsite.co.uk/.htpasswd

<FilesMatch ^index.php\?q=71$>
    require valid-user
</FilesMatch>

The object of the exercise is to protect the following resources:

I have tried various combinations of LocationsMatch, Locations, Files and Filesmatch and can't get it to work.

Thank you in advance


Solution

  • This is what the total solution was:

    If anyone else needs to know, I created a snippet called passwordprotect and put at the top of the page: [[passwordprotect]]. I then put in the following code (an adaptation of the above response):

    <?php
    
    if(isset($_SERVER['PHP_AUTH_USER']) && ($_SERVER['PHP_AUTH_USER']=='user') &&     ($_SERVER['PHP_AUTH_PW']=='password'))
    {
        echo 'You are successfully logged in.';
    } else {
        header('WWW-Authenticate: Basic realm="Protected area"');
        header('HTTP/1.0 401 Unauthorized');
        echo 'Text to send if user hits Cancel button';
        exit;
    }
    

    EDIT: If you are finding that this sometimes does work and sometimes doesn't work, this is probably because using [[passwordprotect]], modx will cache the snippet. I got better success with: [[!passwordprotect]] on Revolution. I think the code is [!passwordprotect!] on Evolution. The exclamation marks just denote not to cache the snippet. Hope that helps someone!