Force url forwarding with htaccess password

Asked

Viewed 807 times

2

I need to test a site that I am creating and for that I will let some people access it, I just want to leave access to a specific url that opens the login of the site.

EX:http://xxxxxx.net/xxxxxx/xxxxx/login.php

Any other form must be blocked.

I need help creating htaccess from this.

Thanks.

3 answers

3

Create a file called ". htpasswd".
The name can be anyone that suits you, not necessarily ". htpasswd".

Paste this into the ". htpasswd":

login:$apr1$pfIh.j7l$Zlqiecx1ZoYfEoUn1QVA50

"login" is the user
"$apr1$pfIh.j7l$Zlqiecx1ZoYfEoUn1QVA50" is an encrypted string. The password is "pass".

In htaccess, add:

AuthType Basic
AuthName "Password Protected Area"
AuthUserFile /caminho/absoluto/do/arquivo/.htpasswd
Require valid-user

That’s enough to start using.

To generate the encrypted password, there are hundreds of sites like this: http://www.htaccesstools.com/htpasswd-generator/. Just search in google "htaccess password Generator" or you can generate without internet use.

*So far we have approached in a superficial way. If you want to know more about the subject, continue with the reading below.






Generating password

For Windows environment, in the Apache installation directory, in the "bin" folder, you will find the executable "htpasswd.exe". By Windows CMD, access the folder of that file, example

cd C:\Apache\httpd-2.4.20-win64-VC14\bin

*The exact location varies according to the installation on your system.

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

The password can have different types of encryption and can even be generated as plain/text, i.e., in "plain text", without encryption. Default is MD5. Note that the chosen password type affects the parameter AuthType, therefore, if you encrypt the password with another format like crypt, set the AuthType equivalent to encryption used. See documentation: http://httpd.apache.org/docs/current/howto/auth.html

*To generate the password in other environments like linux and mac, follow the same logic. Just modify the path of the executable and some features.

Safety tips

The file path . htpasswd must be in a private place with no public access.
For example, if the site index is in c:/www/site/index.php, put the file in a folder outside the public folder

HOW NOT TO:

c:/www/site/.htpasswd

This way, third parties can download the password file. So, avoid putting in a public access location

Suggestion of where to put:

c:/www/.htpasswd

Nomenclature of the password file

The default name is . htpasswd because the default Apache installation checks if this file exists and if it does, it is locked from external access if it is in a public directory. This is for cases where there is an oversight and leave the file with public access.

Despite this, do not fully trust, as not all environments can have the same rule by default. Just in case, leave the file outside the public folder.

For more details on the subject, read the documentation: https://httpd.apache.org/docs/current/programs/htpasswd.html#examples

Allow specific files and directories

To allow open access to specific subdirectories or files, add the URI-based rule:

SetEnvIf Request_URI "(/caminho/completo/do/diretorio1/)$"         allow
SetEnvIf Request_URI "(/caminho/completo/do/diretorio2/)$"         allow
SetEnvIf Request_URI "(/caminho/completo/do/diretorio3/)$"         allow
SetEnvIf Request_URI "(/caminho/completo/aquivo/especifico\.php)$"             allow
Order allow,deny
Allow from env=allow
Satisfy any








An alternative using PHP only

if (
    !isset($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])
    || $_SERVER['PHP_AUTH_USER'] !== 'login'
    || $_SERVER['PHP_AUTH_PW'] !== 'pass'
) {
        header('WWW-Authenticate: Basic realm="Enter username and password."');
        header('Content-Type: text/plain; charset=utf-8');
        echo 'Restricted Area'; exit;
}

In that case you would have to add the script to all the pages you want to lock with the password.

If your system has a router, for example, then just add the code to the router, usually "index.php".

Against

Other files like images, directory access, etc, finally, everything that is not PHP and does not have the script, will have free access.

Despite this, for a general purpose like keeping the site blocked from public access while it is in development or maintenance, it is enough.

Pro

The counterpoint can also be a positive one, as image files are freely accessible, search engines like google can still index images while the system is in temporary maintenance, for example. Thus avoiding losing image rankings and indexes while the site is blocked.

It is also more flexible as it can create conditions directly with PHP, where it is easier to handle. In your case, you want to allow free access to the login.php file. Then it would be enough to create a condition that checks which file name is running and generate the conditions you want.

  • Thanks Daniel, very good your tutorial guy. But I have a doubt here. The basic method you put right at the beginning worked perfect, but I want you to ask for password only at the root (www folder) so that people don’t see my wamp page and the folders listed above, on the way to my site, users can access without password. Got it?

  • In this case you could use the alternative with PHP if possible. If it is not possible, I believe that it is enough to define the rule not to block subdirectories. I added an example in the answer "Allow specific files and directories"

  • Thanks so much for the help man!!

2

I do not think it good to create an htaccess file and in it have the user and its settings, then just copy and paste in the folders you want to block, because at a cost of processing the Web Server to search for these files and then mask them not to be seen, downloaded or edited by customers but centralize them in a single folder and configure it on the site’s Vhosts beyond getting more semantic, saves memory and I see that it is a very good practice applied by IT professionals.

Wamp has a way but it’s kind of complicated since it has many directories hiding Apache advise the Ampps for having a simple and easy directory but finally Serverroot is in C:\wamp\bin\apache\apache2.4.x, it will have to the main folders:

  • \bin - binaries (apachectl) - Executable
  • \conf httpd.conf - Apache Config File
  • \extra conf - Other Config Files
  • C: wamp www - Documentroot

Opens the Prompt de Comando in ServerRoot using SHIPT(Right)+Auxiliary Mouse Button and Follow Commands:

cd C:\wamp\bin\apache\apache2.4.x
md auth

cd bin\
dir ht*

htpasswd -c "..\auth\user.htpasswd" admin
exit

Here you will create a folder called auth and then add a htaccess guy basic, now just get into this file \conf\extra\httpd-vhosts.conf with your favorite editor edit the following line:

    # Raiz do Site
    DocumentRoot c:/wamp/www

    # Configuracao de Arquivos contido no Diretorio
    <Directory  "c:/wamp/www/">
        Options +Indexes +FollowSymLinks +MultiViews
        AllowOverride All

        # So pode acessar se for usuario local pelo IP ::1 (127.0.0.1)
        Require local
    </Directory>

    # Uma pasta acima do Raiz
    <Location "/restrito">
        Options +Indexes
        DirectoryIndex none

        AuthName "Acesso Restrito"
        AuthType Basic

        # Voce pode usar o programa htaccess para criar o banco de dados de senha:
        #   htpasswd -c "..\auth\user.htpasswd" admin
        AuthUserFile "c:\wamp\bin\apache\apache2.4.x\auth\user.htpasswd"

        # So pode acessar se for usuario autenticado
        Require valid-user

        # Redireciona a Pessoa se errar a autenticacao
        ErrorDocument 401 "<html><meta http-equiv=\"refresh\" content=\"0;url=/index.html\"></html>"
        # Redireciona a Pessoa se for usuario autenticado
        Redirect permanent /restrito http://localhost/cpanel
    </Location>

Okay, according to Wamp the httpd-vhost.conf is already active in the Apache Settings httpd.conf, means you can create other Vhosts in this file but if by chance it doesn’t work the restricted try then the full path, I don’t know in this issue of Windows.

  • Whoa, man, thanks for the help!

2


Well depends on the Web Server, if it is the Apache you can put these settings in your VHOST:

 <Directory "/usr/local/apache2/htdocs/seusite.com/">
      Options Indexes FollowSymLinks MultiViews
      Order allow,deny
      Allow from all
 </Directory>

 <Location "/seusite.com/restrito">
      Options +Indexes
      DirectoryIndex none

      AuthName "Acesso Restrito"
      AuthType Basic

      # Você pode usar o programa htaccess para criar o banco de dados de senha:
      #   htpasswd -c "/usr/local/apache2/auth/user.htpasswd" admin
      AuthUserFile "/usr/local/apache2/auth/user.htpasswd"

      # Só pode acessar se for usuário autenticado
      Require valid-user

      # Redireciona a Pessoa se errar a autenticacao
      ErrorDocument 401 "<html><meta http-equiv=\"refresh\" content=\"0;url=/index.html\"></html>"
      # Redireciona a Pessoa se for usuário autenticado
      Redirect permanent /restrito http://seusite.com/cpanel
 </Location>

Then just create a folder in the ServerRoot called auth and by appropriate permissions:

# mkdir -p /usr/local/apache2/auth
# htpasswd -c "/usr/local/apache2/auth/user.htpasswd" admin
# chown root:www-data -R /usr/local/apache2/auth/user.htpasswd
# chmod 640 /usr/local/apache2/auth/user.htpasswd

The idea is that the Apache read line by line and in order, but if you do not want authentication just use the Redirect.

  • Thanks friend for the very complete answer, it would just be a test using wamp (windows). It would not be easier to do this in htaccess?

Browser other questions tagged

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