Force url redirection with htaccess with password

2

I need to test a site that I'm creating and to do this I'll let some people access it, it happens that I only want to give access to a specific url that opens the site login.

EX: link

Any other form should be blocked.

I need help to create htaccess for this.

Thanks.

    
asked by anonymous 06.07.2016 / 13:54

3 answers

2

Well it depends on the Web Server, if it is the Apache you can by 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 ServerRoot called auth and by proper 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 Apache read line by line and in order, but if you do not want authentication, just use Redirect .

    
06.07.2016 / 20:09
3

Create a file named ".htpasswd".
The name can be any one 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 get started.

To generate the encrypted password, there are hundreds of sites like this: link . Just search the google "htaccess password generator" or you can even generate it without internet use.

* So far we have covered superficially. If you would like to know more about it, please continue reading below.

Generating password

For the Windows environment, in the Apache installation directory, in the "bin" folder, you will find the "htpasswd.exe" executable. From the Windows CMD, go to the folder for this file, for example

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

* The exact location varies by installation on your system.

Thepasswordcanhavedifferenttypesofencryptionandcanevenbegeneratedasplain/text,thatis,in"plain text", without encryption. The default is MD5. Note that the type of password chosen affects the AuthType parameter, so if you encrypt the password with another format such as crypt, set the AuthType equivalent to the encryption used. See the documentation: link

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

Safety Tips

The .htpasswd file path must be in a private location, without public access.
Example, if the site index is in c: /www/site/index.php, place the file in a folder outside the public folder

How NOT to do:

c:/www/site/.htpasswd

In this way, third parties can download the password file. Therefore, avoid placing in a publicly accessible location

Suggestion of where to put it:

c:/www/.htpasswd

Password file naming

The default name is .htpasswd because the default Apache installation checks to see if this file exists and if it exists, it is blocked 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.

Nevertheless, 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: link

Allow specific files and directories

To allow free access to specific subdirectories or files, add the rule based on the URI:

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



07.07.2016 / 08:46
2

I do not think it's good to create an htaccess file and have the user and its settings in it, then just copy and paste the folders you want to block, because at a cost of processing the Web Server to look for these files and then mask them so they will not be viewed, downloaded or edited by the clients but if they centralize them in a single folder and configure it in the Vhosts of the site besides being more semantic, it saves memory and I see that it is a very good practice applied by IT professionals.

In Wamp it is like but it is a bit tricky since it has many directories hiding Apache I advise Ampps to have a simple and easy directory but finally ServerRoot stays in C:\wamp\bin\apache\apache2.4.x , it will have to the main folders: / p>

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

Open Prompt de Comando in ServerRoot using SHIPT (Right) + Auxiliary Mouse Button and follow the 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 that is named auth and then add htaccess type basic , now just enter 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>

Now, according to Wamp httpd-vhost.conf is already active in Apache Settings httpd.conf , it means that it can create other Vhosts in this file but if by chance the restricted does not work then try the full path, I do not know how to Windows .

    
07.07.2016 / 07:22