Showing posts with label apache. Show all posts
Showing posts with label apache. Show all posts

Wednesday, December 16, 2009

Installing Magento - Shopping Cart

Magento HOWTO


# Install Apache With It's Documentation #####

$ sudo apt-get install apache2 apache2-doc

# Start Apache (it should already be started) #####
$ sudo /etc/init.d/apache2 start


# Test Apache #####

Type on Mozilla Firefox: http://127.0.0.1/
It souhld read: It works!

Note: The message "It works!" can be found at the /var/www
directorie, which is apaches's root directory, wich is were
we will install Magento.



# Instaling MySQL and PHP necessary Dependencies #####


$ sudo apt-get install mysql-server mysql-client
Type in mySQL's root password in the upcoming textbox.

$ sudo apt-get install libapache2-mod-php5 libapache2-mod-perl2

$ sudo apt-get install php5 php5-cli php5-common php5-curl php5-dev php5-gd php5-imap php5-ldap

$ sudo apt-get install php5-mhash php5-mysql php5-odbc curl libwww-perl imagemagick

$ apt-get install php5-mcrypt

# Creating Magento MySQL Database #####

$ mysql -u root -p

mysql> create database magento;

mysql> exit



# Extract Magento #####

$ cd /home/user/Desktop/magento

$ unzip magento.zip



# Installing Magento in Apache #####

# Copiar o Magento para /var/www (apache root dir)
$ sudo cp -vr magento /var/www



# Give Apache Ownership Over SugarCRM Files (apache-user: www-data) #####

$ sudo chown www-data -vR /var/www/magento*



# Configuring php.ini #####

sudo gedit /etc/php5/apache2/php.ini


;memory_limit = 16M
memory_limit = 64M


# Restart Apache #####

$ sudo /etc/init.d/apache2 restart



# Delete Apache's Test Page #####

$ sudo rm -rf /var/www/index.html


# Configuring Magento #####

Type on Mozilla Firefox:
http://127.0.0.1/magento/install.php
and configure Magento acording to the presented instructions.



Other Shopping Carts Reviews

http://webtecker.com/2008/04/22/8-best-open-source-shopping-cart-solutions/
http://www.siteground.com/shopping_cart_reviews.htm










Tuesday, January 27, 2009

Installing the SMF Forum on Linux

# Install Apache With It's Documentation #####
$ sudo apt-get install apache2 apache2-doc

# Start Apache (it should already be started) #####
$ sudo /etc/init.d/apache2 start


# Test Apache #####

Type on Mozilla Firefox: http://127.0.0.1/
It souhld read: It works!

Note: The message "It works!" can be found at the /var/www
directorie, which is apaches's root directory, wich is were
we will install SMF.



# Instaling MySQL and PHP necessary Dependencies #####

$ sudo apt-get install mysql-server mysql-client
Type in mySQL's root password in the upcoming textbox.

$ sudo apt-get install libapache2-mod-php5 libapache2-mod-perl2

$ sudo apt-get install php5 php5-cli php5-common php5-curl php5-dev php5-gd php5-imap php5-ldap

$ sudo apt-get install php5-mhash php5-mysql php5-odbc curl libwww-perl imagemagick



# Extract SMF #####

$ unzip smf_1-1-7_install.zip



# Installing SMF in Apache #####

# Copy SMF to /var/www (apache root dir)
$ sudo cp -vr smf_1-1-7_install /var/www



# Give Apache Ownership Over SMF Files (apache-user: www-data) #####

$ sudo chown www-data -vR /var/www/smf_1-1-7_install/*


# Restart Apache #####

$ sudo /etc/init.d/apache2 restart


# Delete Apache's Test Page #####

$ sudo rm -rf /var/www/index.html



# Configuring SMF #####

Type on Mozilla Firefox:
http://127.0.0.1/smf_1-1-7_install/install.php
and configure SMF acording to the presented instructions.


Now your forum is on:

http://127.0.0.1/smf_1-1-7_install/index.php
or
http://127.0.0.1/smf_1-1-7_install/

Thursday, January 8, 2009

Installing a Web Application (SugarCRM) on a WebHost

The web application in this example is SugarCRM (SugarCE-5.0.0f) which I already shown how to install on you own host here. Now I'm going to show you how to install it on a WebHost (like BlueHost or others). Installing a web application on a web host is a bit trickier because what you can do on the webhost is very limited.

Im going to assume that you have SugarCRM working on you computer using the howto about installing SugarCRM on your own webhost you can find here. We are going to use this as a basis of comparison between the configs you have localy and the ones on the webhost. You may not need this.


Lets Start...

Create on the webhost the folder SugarCRM, using an FTP client like gftp.

Upload a file php.info (below) on to the folder SugarCRM on the webhost in order to obtain information about the instaled modules and php.ini (/etc/php5/apache2/php.ini) configuration, since you can't access them directly.






Copy the phpinfo.php to your local SugarCRM folder at the apache root (/var/www), not because you are limited but to make it easyer to compare with the webhost config

$ cp /path_to_phpinfo/phpinfo.php /var/www/SugarCRM


Check if the webhost as the apache modules you need

On the browser execute:

http//www.your_domain_on_the_webhost.com/SugarCRM/phpinfo.php

and check the "Loaded Modules" for the needed modules, if you dont now the modules you need execute also:

http://127.0.0.1/SugarCRM/phpinfo.php

and compare the modules you have localy to the the ones on the webhost, the modules you have locally migth not all be needed but if your webhost has them it will work for sure. If there are missing modules contact you webhost and ask them to install them.

Extracting SugarCRM

$ unzip SugarCE-5.0.0f.zip

From now on we are going to prepare on our local machine SugarCRM, in order to upload to the webhost all thats necessary, to minimize the problems.

Defining the read and write permissions on some of SugarCRM's files

$ cd /path_to_extracted_sugar/SugarCE-Full-5.0.0f

$ sudo chmod 766 config.php

$ sudo chmod 766 custom

$ sudo chmod -R 766 data

$ sudo chmod -R 766 cache

$ sudo chmod -R 766 modules


Creating the the SugarCRM sessions directory, seen that by default SugarCRM sessions directory woul be /var/lib/php/session to wich on the webhost we won't have access.

$ cd /path_to_extracted_sugar/SugarCE-Full-5.0.0f

$ mkdir session_save

$ sudo chmod 770 session_save


Configuring php.ini via .htaccess

Seen that we dont have access to php.ini on the webhost (/etc/php5/apache2/php.ini), we are going have to put the configurations we need on the file .htaccess, notice that the configurations on .htaccess only affects the directory where it is and those bellow it.

In order to now what to put on .htaccess, what I did was, execute the phpinfo.php on my local SugarCRM folder and the Webhost, like this:

http:/www.your_domain_on_the_webhost.com/SugarCRM/phpinfo.php (Webhost SugarCRM)

http://127.0.0.1/phpinfo.php (Local SugarCRM)

And saw the differences between the different variables in "Configuration - PHP Core" (php.ini config), and changed the ones in the webhost that were different to the value the local ones had. They not all be needed but if it work locally on the web host should work to. The result was the following .htaccess:

.htaccess - put in /path_to_extracted_sugar/SugarCE-Full-5.0.0f
--------------------------------------------------------------------

php_value memory_limit 50M
php_value upload_max_filesize 10M
php_value allow_call_time_pass_reference On
php_value allow_url_fopen On
php_value display_errors On
php_value enable_dl On
php_value magic_quotes_gpc On
php_value register_long_arrays On
php_value safe_mode Off
php_value session.save_path /home/my_ftp_user_name/SugarCRM/session_save

The last value php_value session.save_path you have to ask to you webhost, where on in their machine is the top folder you access via FTP, which in my case is /home/my_user_name/, the rest is same (SugarCRM/session_save). Or you can always try to gess it /home/your_ftp_user_name.


Nowing that after the upload of SugarCRM to the webhost in order for SugarCRM to work, like any other webapp, the must be owned by the apache user. Now the problem is, that if apache owns the the files you wont be able to access the if there's some kind of problem, or even delete them.

My solution for this problem is giving the same read,write, execute permitions that the owner has, to the group and being a part of this group, like this you will have the same permitions you had before apache became the owner of the files.

In order to do that we are going to use the following script:

usertogroup
---------------------
#!/bin/ksh
echo "Enter Base Directory: "
read source_dir
for file in `find $source_dir`
do
#full=`ls -ld $file |awk '{print $1}'`
owner=`ls -ld $file | cut -c2-4`
#echo "$full $file ----------------> chmod g+$owner $file"
chmod g+$owner $file
done

$ sudo chmod 777 usertogroup

$ sh usertogroup
Enter Base Directory:
/path_to_extracted_sugar/SugarCE-Full-5.0.0f


Now that we have SugarCRM prepared in our computer, lets upload the contents off /path_to_extracted_sugar/SugarCE-Full-5.0.0f to the SugarCRM
folder that we created before, using an FTP client like gFTP.

The folowing steps you have to ask the webhost to do the following:

- Change the owner of all of the SugarCRM files to the apache user

- Add our username to the group that the file belongs to.


Now you should be able to configure SugarCRM, by executing the following in the browser:

http://www.your_domain_on_the_webhost.com/SugarCRM/install.php

and configure SugarCRM, once configure you can access SugarCRM's main page by executing the following in the web browser:

http://www.your_domain_on_the_webhost.com/SugarCRM/index.php

OR

http://www.your_domain_on_the_webhost.com/SugarCRM

And thats it, now you sould have SugarCRM up and running.

Tuesday, July 29, 2008

Installing AddressBook

Here we have how to install:


- AddressBook v4.0
- AddressBook v3.1.5


AdressBook v4.0 HOWTO

# Install Apache with it's documentation #####
$ sudo apt-get install apache2 apache2-doc


# Start Apache (it should already be started) #####
$ sudo /etc/init.d/apache2 start


# Test Apache #####

Type in on Mozilla Firefox: http://127.0.0.1/
It should read: It works!

Nota: The page "It works!" is at /var/www,
which is apaches root directory,
so this is where we will put the addressbook.





# Install the needed MySQL e PHP dependencies #####

$ sudo apt-get install mysql-server mysql-client
Type MySQL root password in the upcoming textbox.

$ sudo apt-get install libapache2-mod-php5 libapache2-mod-perl2

$ sudo apt-get install php5 php5-cli php5-common php5-curl php5-dev php5-gd php5-imap php5-ldap

$ sudo apt-get install php5-mhash php5-mysql php5-odbc curl libwww-perl imagemagick


# Download the AdressBook (http://sourceforge.net/projects/php-addressbook/)

$ cd ~/Desktop

$ wget http://downloads.sourceforge.net/php-addressbook/addressbookv4.0.zip?modtime=1212528743&big_mirror=0



# Extrair o AddressBook #####

$ cd ~/Desktop

$ unzip addressbookv4.0.zip



# Install o AdressBook no Apache #####

# Copiar o AdressBook para /var/www (apache root dir)
$ sudo cp -vr addressbookv4.0 /var/www


# Give Apache (apache-user: www-data) permitions over the AddressBook files #####

$ sudo chown www-data -vR /var/www/addressbookv4.0/*



# Configure the AdressBook #####


# Create AddressBook's database #####

$ mysql -u root -p

mysql> create database addressbook_db;

mysql> exit



# Configure AddressBook's connection to the database #####

$ sudo gedit /var/www/addressbookv4.0/config/config.php

No ficheiro:

// Database access definition
// $dbname = "your_database";
// $dbserver = "localhost";
// $dbuser = "username";
// $dbpass = "password";


// Database access definition
$dbname = "addressbook_db";
$dbserver = "localhost";
$dbuser = "root";
$dbpass = "12314467";



# Create the necessary table at the AdressBook's database #####

$ mysql addressbook_db -u root -p < /var/www/addressbookv4.0/addressbook.sql



# Restart Apache #####

$ sudo /etc/init.d/apache2 restart



# Delete the test page #####

$ sudo rm -rf /var/www/index.html



# Configure AdressBook #####

On Mozilla Firefox type in:
http://127.0.0.1/addressbookv4.0 ou http://127.0.0.1/addressbookv4.0/index.php
now just configure addressbook acording to the presented instructions.



AdressBook v3.1.5 HOWTO

# Install Apache with it's documentation #####
$ sudo apt-get install apache2 apache2-doc

# Start Apache (it should already be started) #####
$ sudo /etc/init.d/apache2 start


# Test Apache #####

Type in on Mozilla Firefox: http://127.0.0.1/
It should read: It works!

Nota: The page "It works!" is at /var/www,
which is apaches root directory,
so this is where we will put the addressbook.




#Install the needed MySQL e PHP dependencies #####

$ sudo apt-get install mysql-server mysql-client
Type MySQL root password in the upcoming textbox.

$ sudo apt-get install libapache2-mod-php5 libapache2-mod-perl2

$ sudo apt-get install php5 php5-cli php5-common php5-curl php5-dev php5-gd php5-imap php5-ldap

$ sudo apt-get install php5-mhash php5-mysql php5-odbc curl libwww-perl imagemagick




# Download the AddressBook (http://sourceforge.net/projects/php-addressbook/)

$ cd ~/Desktop

$ wget http://downloads.sourceforge.net/php-addressbook/addressbookv3.1.5.zip?modtime=1212528743&big_mirror=0



# Extract the AddressBook #####

$ cd ~/Desktop

$ unzip addressbookv3.1.5.zip



# Install AddressBook on Apache #####

# Copiar o AdressBook para /var/www (apache root dir)

$ sudo cp -vr addressbookv3.1.5 /var/www


# Give Apache (apache-user: www-data) permitions over the AddressBook files #####

$ sudo chown www-data -vR /var/www/addressbookv4.0/*



# Configure the AdressBook #####

# Create AddressBook's database #####

$ mysql -u root -p

mysql> create database addressbook_db;

mysql> exit



# Configure AddressBook's connection to the database #####

$ sudo gedit /var/www/addressbookv3.1.5/include/config.php

Change the following at the file:

// Database access definition
// $dbname = "your_database";
// $dbserver = "localhost";
// $dbuser = "username";
// $dbpass = "password";


// Database access definition
$dbname = "addressbook_db";
$dbserver = "localhost";
$dbuser = "root";
$dbpass = "12314467";



# Create the necessary table at the AdressBook's database #####

$ mysql addressbook_db -u root -p < /var/www/addressbookv3.1.5/addressbook.sql



# Restart Apache #####

$ sudo /etc/init.d/apache2 restart



# Delete the test page #####

$ sudo rm -rf /var/www/index.html



# Configure AdressBook #####

On Mozilla Firefox type in :

http://127.0.0.1/addressbookv3.1.5
or http://127.0.0.1/addressbookv3.1.5/index.php

now just configure addressbook acording to the presented instructions.

Monday, July 14, 2008

SugarCRM 5.0.0f on Ubuntu 8.04 (Hardy Heron)

SugarCRM HOWTO


# Install Apache With It's Documentation #####
$ sudo apt-get install apache2 apache2-doc

# Start Apache (it should already be started) #####
$ sudo /etc/init.d/apache2 start


# Test Apache #####

Type on Mozilla Firefox: http://127.0.0.1/
It souhld read: It works!

Note: The message "It works!" can be found at the /var/www
directorie, which is apaches's root directory, wich is were
we will install SugaCRM.



# Instaling MySQL and PHP necessary Dependencies #####

$ sudo apt-get install mysql-server mysql-client
Type in mySQL's root password in the upcoming textbox.

$ sudo apt-get install libapache2-mod-php5 libapache2-mod-perl2

$ sudo apt-get install php5 php5-cli php5-common php5-curl php5-dev php5-gd php5-imap php5-ldap

$ sudo apt-get install php5-mhash php5-mysql php5-odbc curl libwww-perl imagemagick



# Creating SugarCRM MySQL Database #####

$ mysql -u root -p

mysql> create database sugarcrm;

mysql> exit



# Extract SugarCRM #####

$ cd /home/jose/Desktop/SugarCRM

$ unzip SugarCE-5.0.0f.zip



# Installing SugarCRM in Apache #####

# Copiar o SugarCRM para /var/www (apache root dir)
$ sudo cp -vr SugarCE-Full-5.0.0f /var/www



# Give Apache Ownership Over SugarCRM Files (apache-user: www-data) #####

$ sudo chown www-data -vR /var/www/SugarCE-Full-5.0.0f/*




# Write Permitions for Apache on Some of SugarCRM Files #####

$ cd /var/www/SugarCE-Full-5.0.0f

$ sudo chmod 766 config.php

$ sudo chmod 766 custom

$ sudo chmod -R 766 data

$ sudo chmod -R 766 cache

$ sudo chmod -R 766 modules



# Restart Apache #####

$ sudo /etc/init.d/apache2 restart



# Delete Apache's Test Page #####

$ sudo rm -rf /var/www/index.html



# Configuring php.ini #####

sudo gedit /etc/php5/apache2/php.ini


;memory_limit = 16M
memory_limit = 50M

;upload_max_filesize = 2M
upload_max_filesize = 10M



# Configuring SugarCRM #####

Type on Mozilla Firefox:
http://127.0.0.1/SugarCE-Full-5.0.0f/install.php
and configure SugarCRM acording to the presented instructions.

Friday, July 4, 2008

Apache - Basic Authentication - htaccess

Uso e Segurança com o .htaccess no Apache

Hugo Cisneiros, hugo_arroba_devin_ponto_com_ponto_br
Última atualização em 01/08/2003

1. Introdução

Oi pessoal, neste tutorial vou tocar em alguns métodos dee segurança com os arquivos .htaccess do Apache, para proteger diretórios na Web, criar meios de login controlado, e outras utilidades deeste arquivo.

O .htaccess é um arquivo especial para o Apache. Quando um usuário está navegando por alguma página do seu servidor Apache, para todo diretório que ele tentar acessar (e se o servidor estiver configurado para isso), o Apache procura pelo tal do .htaccess e se encontrar, verifica alguma restrição ou liberação para o usuário. Com isso podemos fazer duas coisas básicas em relação à segurança: Restringir acesso aos arquivos e diretórios do servidor Web através de um usuário e senha, ou então pelo IP/Hostname de quem está acessando. Trataremos dos dois assuntos aqui neste tutorial.

2. Configurando o Apache

Antes de mais nada, você precisará se certificar que o Apache está configurado para aceitar os arquivos .htaccess como arquivos especiais. Para configurar, você precisará editar o arquivo de configuração do Apache, que é o "httpd.conf". Geralmente ele está localizado no diretório "/etc/httpd/conf". Dentro deste arquivo, você encontrará uma ou duas diretrizes mais ou menos desta forma:


Options FollowSymLinks
AllowOverride None

ou


Options Indexes FollowSymLinks
AllowOverride None
Order allow,deny
Allow from all

Nesta configuração do Apache, tudo que está dentro das significa restrtições e opções especialmente configuradas para aquele diretório. No caso acima, eu estou aplicando algumas regras tanto no diretório base do servidor Web (ou seja, todo o servidor Web, independente do domínio virtual ou qualquer outra coisa), como também estou aplicando no diretório "/var/www/html", que aqui no caso é onde ficam as páginas Web. Então cabe a você decidir escolher entre as duas diretrizes (ou utilizar a configuração nova nas duas diretrizes mesmo, ou até então criar uma diretriz nova). Como eu quero ativar o .htaccess em todo o meu servidor Web, vou colocar da seguinte maneira:


Options FollowSymLinks Indexes
AllowOverride AuthConfig

O que eu fiz aqui foi adicionar a opção "Indexes" neste diretório e colocar o valor "AuthConfig" no AllowOverride. Em "Options", eu digo algumas opções extras que podem ser colocadas neste diretório. Isso não tem muito haver com este tutorial e nem é necessário, mas é sempre bom saber alguma coisa a mais se já não se sabe :)

Como a própria documentação do Apache diz, podemos usar as seguintes opções para diretórios: "None", "All", ou qualquer combinação de "Indexes", "Includes", "FollowSymLinks", "ExecCGI", or "MultiViews". A opção "Indexes" faz com que quando não tiver nenhum arquivo do tipo index.html, index.htm, ou "páginas iniciais", o Apache cria uma página com a lista dos arquivos existentes no diretório. O "Includes" permite colocar arquivos do tipo SSI (Server Side Includes), que são páginas dinâmicas antigamente usadas por muitos (Agora a moda é PHP, Python, Perl, etc). O "FollowSymLinks" faz com que o Apache aceite links simbólicos no sistema, seguindo os diretórios ou arquivos que os links apontam. O "ExecCGI" faz com que neste diretório possam ser executados arquivos CGI (Common Gateway Interface). A opção ExecCGI pode ser (e geralmente é) encontrada para o diretório "/var/www/cgi-bin", onde estão localizados os scripts CGI. Já o "multiViews" serve para por exemplo, servir páginas de acordo com a preferência de língua do usuário (index.html.pt_BR, indeex.html.en, etc).

O All significa todas as opções (menos o MultiViews) e o None significa nenhuma :)

Deixando de lado essa parte, vamos ao que realmente interessa. A opção "AllowOverride AuthConfig" é a que diz para o Apache verificar pelos arquivos .htaccess nos diretórios e aplicar as regras contidas no arquivo nos diretórios e subdiretórios de onde o arquivo esteja localizado. Colocada esta opção, é só dar um restart ou reload no servidor Web e tudo funcionará.

Para fins de entendimento, o nome "AllowOverride" já diz tudo: Ele sobrescreve as configurações padrões do servidor Apache para colocar novas configurações para aquele diretório. Estas configurações podem ser permissões dee acesso, opções (como as que mostrei acima), entre outros.

3. Utilizando o .htaccess

Agora que o servidor Apache já está configurado, teremos que criar o arquivo .htaccess com as regras. Utilize o seu editor prefeiro (no meu caso, o vim). Poderemos fazer várias coisas neste arquivo. Neste tutorial estarei usando vários arquivos .htaccess para demonstrar cada opção à cada caso, mas você pode utilizar um .htaccess no diretório principal do seu servidor, e definir as permissões e opções colocando-as dentro de tags , , etc. Tentarei dar alguns exemplos aqui.

3.1. Restringindo o acesso por IP/Hostname

As vezes precisamos restringir certos arquivos e diretórios para cecrtos IPs. Isso é válido por exemplo, quando você tem um provedor, e só se quer permitir acessar algumas páginas de administração os IPs da Intranet do provedor. Para isso pode-se aplicar estas regras no .htaccess. Veja o exemplo abaixo:

# Deixa a Intranet acessar
Order allow,deny
allow from 192.168.0.
deny from all

Esse exemplo de .htaccess fará com que o diretório, seus arquivos e seus subdiretórios só poderão ser acessados por quem estiver na faixa de IP de 192.168.0.1 até 192.168.0.254. Vamos supor agora que eu queira restringir apenas 1 IP, para não acessar um certo diretório. O .htaccess ficaria assim:

# Deixa todo mundo acessar, menos o IP 192.168.0.25
Order deny,allow
deny from 192.168.0.25
allow from all

E está feito, quando o IP 192.168.0.25 tentar acessar, não vai conseguir. Você pode substituir o IP por um hostname, contanto que a opção "HostnameLookups" no httpd.conf esteja habilitada (on).

3.2. Restringindo o acesso por usuário e senha

Agora vem uma parte muito interessante. As vezes não temos como restringir apenas por IPs, seja porque o usuário que tem que acessar possa etar em qualquer lugar, ou ter IP dinâmico, etc. Para resolver esse caso, podemos utilizar o método de usuário e senha. Antes de mais nada você terá que ter o utilitário "htpasswd", que serve para criar um arquivo de senhas criptografadas. Neste tutorial, criaremos 3 usuários exemplo:

$ mkdir /etc/httpd/auth
$ cd /etc/httpd/auth

$ htpasswd -c acesso hugo
New password:
Re-type new password:
Adding password for user hugo

$ htpasswd acesso eitch
New password:
Re-type new password:
Adding password for user eitch

$ htpasswd acesso sakura
New password:
Re-type new password:
Adding password for user sakura

O resultado que temos é o arquivo /etc/httpd/auth/acesso com o seguinte conteúdo:

hugo:zEerw0euqYD3k
eitch:85QVc5DD0rB8M
sakura:UpZuXkyuIq9hw
Observação: Caso você não tenha o utilitário htpasswd, você pode criar as senhas criptografadas com um comando do perl. Por exemplo, se eu quiser criar a senha criptografada chamada "minhasenha", farei o seguinte comando:
$ perl -e 'print crypt("minhasenha", "Lq"), "\n";'

E então é só incluir a senha no arquivo como no esquema acima.

Como pode ver, as senhas estão criptografadas. Este armazenamento de senhas é muito simples. Há outros métodos de se armazenar senhas (arquivos de banco de dados por exemplo), mas por enquanto não vou cobrir isto no tutorial porque não é tão necessário. Mas fica extremamente necessário se houver muitos e muitos usuários e senhas, pois se houver muitos, o processo de autenticação pode demorar um pouco.

Agora que o arquivo de usuários e senhas está criado, vamos criar o .htaccess que irá verificar este arquivo. Veja o exemplo do .htaccess:

AuthName "Acesso Restrito à Usuários"
AuthType Basic
AuthUserFile /etc/httpd/auth/acesso
require valid-user

Salve o arquivo e pronto, quando um usuário acessar a URL, o servidor irá verificar este arquivo .htaccess e irá perguntar pro cliente um usuário e senha. Epa, mas peraí, vamos explicar direitinho o arquivo acima!

  • AuthName: O nome que aparece como mensagem de Login. Pode usar algo como "Entre com Login e Senha", ou coisa deste tipo.
  • AuthType: Tipo de autenticação. Atualmente o Basic é o tipo mais comum. Existe também o "Digest", mas ainda não é muito utilizado e suportado pelos clientes.
  • AuthUserFile: Onde está o arquivo de usuários e senhas que agente criou.
  • require valid-user: O que o Apache precisa para validar o acesso. Neste caso a gente indicou que precisa de um usuário válido para acessar a página, ou seja, alguém que digitou um usuário e senha e bateu com o que está no arquivo de senhas. Pode-se restringir para apenas alguns usuários do arquivo de senhas. Por exemplo, se eu quisesse restringir apenas para o usuário eitch e sakura, ao invés de "require valid-user", ficaria "require user eitch sakura".

Mas se por acaso você tiver muitos usuários, e quer dividí-los em grupos, você pode muito bem fazer isso! Primeiro teremos que criar o arquivo com os grupos. Use o seu editor preferido, e vamos criar por exemplo, o arquivo "/etc/httpd/auth/grupos":

admin:hugo eitch
visitante: sakura
empresa: hugo eitch sakura

Salve o arquivo e então criamos três grupos. Para usar estes grupos, teremos que modificar o arquivo .htaccess anterior para ficar desta maneira:

AuthName "Acesso Restrito à Usuários"
AuthType Basic
AuthUserFile /etc/httpd/auth/acesso
AuthGroupFile /etc/httpd/auth/grupos
require group admin

No arquivo acima eu adicionei a linha "AuthGroupFile", que indica pro servidor onde está o arquivo dos grupos (bem parecido com o "AuthUserFile" hein?) e no "require", coloquei que requer o grupo admin. Simples de entender, não? Agora já dá pra brincar bastante restringindo usuários :)

3.3. Opções diferentes

Lembra do "Options" na diretriz no tópico 2? Pois é, você pode colocar estas opções também no .htaccess. Se por exemplo você quer que o diretório onde você colocou o .htaccess liste os arquivos caso não haja um index.html da vida, você adiciona o seguinte no .htaccess:

Options +Indexes

E para tirar essa opção:

Options -Indexes

E nisso você pode usar para qualquer uma das opções.

3.4. Mensagens de Erro personalizadas

Vamos supor que você tenha uma sub-página no seu servidor, e queira que as mensagens de erro do servidor sejam bonitinhas e no formato que você criou. Para fazer isso, você precisará apenas saber o que significa cada código de erro do servidor e apontar para a uma página com o .htaccess:

ErrorDocument 401 /erros/falhaautorizacao.html
ErrorDocument 404 /erros/naoencontrado.html
ErrorDocument 403 /erros/acessonegado.html
ErrorDocument 500 /erros/errointerno.html

Caso você não saiba os códigos de erro do Apache, a configuração do apache 2.x já tem uma boa ajuda quanto a isto, vou colocar as linhas aqui como referência (entenda se quiser e puder :P):

ErrorDocument 400 /error/HTTP_BAD_REQUEST.html.var
ErrorDocument 401 /error/HTTP_UNAUTHORIZED.html.var
ErrorDocument 403 /error/HTTP_FORBIDDEN.html.var
ErrorDocument 404 /error/HTTP_NOT_FOUND.html.var
ErrorDocument 405 /error/HTTP_METHOD_NOT_ALLOWED.html.var
ErrorDocument 408 /error/HTTP_REQUEST_TIME_OUT.html.var
ErrorDocument 410 /error/HTTP_GONE.html.var
ErrorDocument 411 /error/HTTP_LENGTH_REQUIRED.html.var
ErrorDocument 412 /error/HTTP_PRECONDITION_FAILED.html.var
ErrorDocument 413 /error/HTTP_REQUEST_ENTITY_TOO_LARGE.html.var
ErrorDocument 414 /error/HTTP_REQUEST_URI_TOO_LARGE.html.var
ErrorDocument 415 /error/HTTP_SERVICE_UNAVAILABLE.html.var
ErrorDocument 500 /error/HTTP_INTERNAL_SERVER_ERROR.html.var
ErrorDocument 501 /error/HTTP_NOT_IMPLEMENTED.html.var
ErrorDocument 502 /error/HTTP_BAD_GATEWAY.html.var
ErrorDocument 503 /error/HTTP_SERVICE_UNAVAILABLE.html.var
ErrorDocument 506 /error/HTTP_VARIANT_ALSO_VARIES.html.var

3.5. Opções para arquivos e diretórios específicos

Agora vamos supor que você queira somente fazer restrições para certos arquivos e diretórios. Para isso você poderá fazer tudo o que fazia antes, só que dentro de tags como ou . Veja o exemplo de .htaccess a seguir com comentários embutidos explicando o contexto:

# Restringe o arquivo_secreto.html somente para o IP 192.168.0.30

Order allow,Deny
Allow from 192.168.0.30
Deny from all


# Restringe o diretório admin para utilizar senhas

AuthName "Acesso Restrito à Usuários"
AuthType Basic
AuthUserFile /etc/httpd/auth/acesso
AuthGroupFile /etc/httpd/auth/grupos
require group admin


# Nega o acesso dos clientes ao .htaccess (bom colocar no httpd.conf)
# - Vem com a configuração padrão do Apache

Order allow,deny
Deny from all

Entendeu bem como funciona o esquema? Então é só brincar bastante :)

4. Conclusão

Pudemos aprender bastante como mexer com o .htaccess, mas o que vimos aqui não foi tudo não. Tem muita coisa ainda que se dá para colocar no .htaccess. Como eu disse no início dedste tutorial, o .htaccess poded comportar todo tipo de configuração de diretórios do Apache, sobrescrevendo as configurações padrões contidas no httpd.conf. Explorar as funcionalidades é uma questão de prática, então mãos a obra!

Bom proveito!