block access to a particular directory via htaccess with password

Asked

Viewed 456 times

0

I currently have a server where I leave my web projects running, some of them in Laravel, so far without problems, however I want to create a password restriction on .htaccess to the root,

For example:

I have the domains site_a.dominio.com.br, site_b.dominio.com.br and dominio.com.br, where site_a and site_b are virtual apache hosts and the dominio.com.br return to root www.

Both the site_a as to the site_b no password is required for page loading dominio.com.br, when opening the password is requested by the browser, and if possible the setting of user and password in the .htaccess.

2 answers

0

I think what you want is a way to not index the domain home page, you can put an "index.php" to authenticate and create in the same an algorithm to list the folder on the web.

Follow a script I prepared for you

<?php
$realm = 'Área restrita';

//usuário => senha
$users = array('admin' => 'senha', 'visitante' => 'senha');


function authNow() {
    global $realm;
    header('HTTP/1.1 401 Unauthorized');
    header('WWW-Authenticate: Digest realm="'.$realm.'",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
    die('Não foi possível validar seus dados');
}

if (empty($_SERVER['PHP_AUTH_DIGEST'])) {
    authNow();
}


// analisar a variável PHP_AUTH_DIGEST
if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) ||
    !isset($users[$data['username']])) {
    authNow();
}


// gerar a resposta válida
$A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]);
$A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']);
$valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2);

if ($data['response'] != $valid_response) {
    authNow();
}


// listando diretórios
$dirs = array_filter(glob('*'), 'is_dir');
echo '<h1>Início em /</h1><hr/>';
echo '<ul>';
foreach($dirs as $dir) {
    echo '<li><a href="'.$dir.'">' . $dir . '</a></li>';
}
echo '</ul><hr/>Página gerada em ' . date('d/m/Y H:i:s');


// função para decompor o http auth header
function http_digest_parse($txt)
{
    // proteção contra dados incompletos
    $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
    $data = array();
    $keys = implode('|', array_keys($needed_parts));

    preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@', $txt, $matches, PREG_SET_ORDER);

    foreach ($matches as $m) {
        $data[$m[1]] = $m[3] ? $m[3] : $m[4];
        unset($needed_parts[$m[1]]);
    }

    return $needed_parts ? false : $data;
}
  • Boys thanks for the help, but yes it is possible yes, with the use of Linux password I can even make put in one of the companies my boss did so and becomes practical for simple things.

0


After a little search, I ended up finding the solution to my problem, so I came to share with the community, (which was even better than I expected)

.htaccess:

# bloquando leitura do .hacess
<files ~ "^.*\.([Hh][Tt][Aa])">
    order allow,deny
    deny from all
    satisfy all
</files>

# Solicitando apenas Quando for a raiz do dominio
<If "req('Host') == 'dominio.com.br'">
    AuthType Basic
    AuthName "Password Protected Area"
    AuthUserFile /home/bull/.htpasswd
    Require valid-user
</If>
<Else>
    Require all granted
</Else>

For security reasons it was added to block the reading of the file itself .htaccess,

The logic applied for the password request is, if the requested URL is for example: dominio.com.br, it will prompt for the password if not, (in short the subdomains or local access by the internal ip of the server) it will open load the pages without the need for the password.

References:

https://stackoverflow.com/questions/1359472/use-http-auth-only-if-accessing-a-specific-domain?answertab=oldest#tab-top

https://www.codigofonte.com.br/artigos/confira-20-dicas-e-truques-extremamente-uteis-do-htaccess

Browser other questions tagged

You are not signed in. Login or sign up in order to post.