Instalação e Configuração do Apache + MySQL + PHP + SSL no FreeBSD 9.0

Aqui eu vou abordar a Instalação e configuração do servidor Apache com suporte ao PHP, MySQL e SSL no FreeBSD 9.0 vou levar em consideração que o seu sistema já está configurado e tem os ports instalados e atualizados

Vamos obter os ports e mandar atualizar eles

portsnap fetch && portsnap extract && portsnap update

Agora vamos acessar o diretório

cd /usr/ports/ports-mgmt/portaudit

Vamos compilar ele e instalar o portaudit

make install distclean

Agora vamos atualizar as variáveis de nosso ambiente caso esteja utilizando o csh como shell

source /root/.cshrc

Agora vamos fazer uma auditoria de nosso ports

portaudit -Fda

Vamos acessar o ports do apache

cd /usr/ports/www/apache22

Agora vamos mandar instalar ele, deixe as opções padrões do apache

make install distclean

Nas opções que aparecerem das dependências deixe selecionada as padrões

Após terminar o processo vamos ter algo como abaixo

===> Installing rc.d startup script(s)
To run apache www server from startup, add apache22_enable="YES"
in your /etc/rc.conf. Extra options can be found in startup script.

Your hostname must be resolvable using at least 1 mechanism in
/etc/nsswitch typically DNS or /etc/hosts or apache might
have issues starting depending on the modules you are using.
===> Correct pkg-plist sequence to create group(s) and user(s)
===>   Compressing manual pages for apache22-2.2.23
===>   Registering installation for apache22-2.2.23
===>  Cleaning for apr-1.4.6.1.4.1_1
===>  Cleaning for gdbm-1.9.1
===>  Cleaning for db42-4.2.52_5
===>  Cleaning for apache22-2.2.23
===>  Deleting distfiles for apache22-2.2.23
make install distclean  147.89s user 66.70s system 49% cpu 7:12.45 total

Agora vamos deixar os módulos de suporte ao apache na inicialização do sistema

echo 'accf_http_load="YES"' >> /boot/loader.conf
echo 'accf_data_load="YES"' >> /boot/loader.conf

Agora vamos carregar eles para sessão corrente

kldload accf_http
kldload accf_data

Agora vamos mandar instalar o php vamos acessar o diretório do ports que contem o php

cd /usr/ports/lang/php5

Agora vamos mandar instalar ele, não esqueça de marcar o suporte ao apache

make install distclean

Após terminar a instalação vamos ter algo como abaixo

***************************************************************

Make sure index.php is part of your DirectoryIndex.

You should add the following to your Apache configuration file:

AddType application/x-httpd-php .php
AddType application/x-httpd-php-source .phps

***************************************************************
===>   Compressing manual pages for php5-5.4.7
===>   Registering installation for php5-5.4.7
===> SECURITY REPORT: 
      This port has installed the following files which may act as network
      servers and may therefore pose a remote security risk to the system.
/usr/local/libexec/apache22/libphp5.so
/usr/local/bin/php
/usr/local/bin/php-cgi

      If there are vulnerabilities in these programs there may be a security
      risk to the system. FreeBSD makes no guarantee about the security of
      ports included in the Ports Collection. Please type 'make deinstall'
      to deinstall the port if this is a concern.

      For more information, and contact details about the security
      status of this software, see the following webpage: 
http://www.php.net/
===>  Cleaning for php5-5.4.7
===>  Deleting distfiles for php5-5.4.7
make install distclean  98.76s user 40.77s system 76% cpu 3:02.18 total

Agora vamos mandar instalar as extensões do php escolha as que forem necessárias, não esqueça de marcar o suporte ao MySQL

cd /usr/ports/lang/php5-extensions && make install distclean

Caso apareça alguma opção das dependências deixe marcado as padrões

Quando terminar a instalação vamos ter algo como abaixo

****************************************************************************
===>   Returning to build of php5-extensions-1.7
===>  Configuring for php5-extensions-1.7
===>  Installing for php5-extensions-1.7
===>   php5-extensions-1.7 depends on file: /usr/local/include/php/main/php.h - found
===>   php5-extensions-1.7 depends on file: /usr/local/lib/php/20100525/ctype.so - found
===>   php5-extensions-1.7 depends on file: /usr/local/lib/php/20100525/dom.so - found
===>   php5-extensions-1.7 depends on file: /usr/local/lib/php/20100525/filter.so - found
===>   php5-extensions-1.7 depends on file: /usr/local/lib/php/20100525/hash.so - found
===>   php5-extensions-1.7 depends on file: /usr/local/lib/php/20100525/iconv.so - found
===>   php5-extensions-1.7 depends on file: /usr/local/lib/php/20100525/mysql.so - found
===>   php5-extensions-1.7 depends on file: /usr/local/lib/php/20100525/pdo.so - found
===>   php5-extensions-1.7 depends on file: /usr/local/lib/php/20100525/pdo_sqlite.so - found
===>   php5-extensions-1.7 depends on file: /usr/local/lib/php/20100525/phar.so - found
===>   php5-extensions-1.7 depends on file: /usr/local/lib/php/20100525/posix.so - found
===>   php5-extensions-1.7 depends on file: /usr/local/lib/php/20100525/session.so - found
===>   php5-extensions-1.7 depends on file: /usr/local/lib/php/20100525/simplexml.so - found
===>   php5-extensions-1.7 depends on file: /usr/local/lib/php/20100525/sqlite3.so - found
===>   php5-extensions-1.7 depends on file: /usr/local/lib/php/20100525/tokenizer.so - found
===>   php5-extensions-1.7 depends on file: /usr/local/lib/php/20100525/xml.so - found
===>   php5-extensions-1.7 depends on file: /usr/local/lib/php/20100525/xmlreader.so - found
===>   php5-extensions-1.7 depends on file: /usr/local/lib/php/20100525/xmlwriter.so - found
===>   Generating temporary packing list
===>  Checking if lang/php5-extensions already installed
===>   Registering installation for php5-extensions-1.7
===>  Cleaning for php5-ctype-5.4.7
===>  Cleaning for php5-dom-5.4.7
===>  Cleaning for php5-filter-5.4.7
===>  Cleaning for php5-hash-5.4.7
===>  Cleaning for php5-iconv-5.4.7
===>  Cleaning for php5-mysql-5.4.7
===>  Cleaning for php5-pdo-5.4.7
===>  Cleaning for php5-pdo_sqlite-5.4.7
===>  Cleaning for php5-phar-5.4.7
===>  Cleaning for php5-posix-5.4.7
===>  Cleaning for php5-session-5.4.7
===>  Cleaning for php5-simplexml-5.4.7
===>  Cleaning for php5-sqlite3-5.4.7
===>  Cleaning for php5-tokenizer-5.4.7
===>  Cleaning for php5-xml-5.4.7
===>  Cleaning for php5-xmlreader-5.4.7
===>  Cleaning for php5-xmlwriter-5.4.7
===>  Cleaning for sqlite3-3.7.14.1
===>  Cleaning for php5-extensions-1.7
===>  Deleting distfiles for php5-extensions-1.7
make install distclean  142.87s user 59.45s system 68% cpu 4:53.51 total

Agora vamos acertar a localizacao do php.ini

cp /usr/local/etc/php.ini-production /usr/local/etc/php.ini

Agora vamos acertar a configuração do apache

vim /usr/local/etc/apache22/httpd.conf
[...]
<IfModule dir_module>
DirectoryIndex index.php index.php5 index.htm index.html
</IfModule>
[...]
    AddType application/x-compress .Z
    AddType application/x-gzip .gz .tgz
    [...]
    AddType application/x-httpd-php .php
    AddType application/x-httpd-php-source .phps
[...]
#Descomentar a linha abaixo
Include etc/apache22/extra/httpd-vhosts.conf
#Descomentar a linha abaixo
Include etc/apache22/extra/httpd-default.conf

Acertar a assinatura do apache

vim /usr/local/etc/apache22/extra/httpd-default.conf
[...]
ServerTokens Prod
[...]
ServerSignature Off

Vamos fazer um backup do arquivo de configuração de virtualhost de exemplo

cp /usr/local/etc/apache22/extra/httpd-vhosts.conf /usr/local/etc/apache22/extra/httpd-vhosts.conf.old

Agora vamos criar o nosso virtualhost do apache deixe o arquivo como abaixo

vim /usr/local/etc/apache22/extra/httpd-vhosts.conf
#Habilitando escutar na porta 443 https
Listen 443

#Configuracoes do https
AddType application/x-x509-ca-cert .crt
AddType application/x-pkcs7-crl .crl
SSLPassPhraseDialog builtin
SSLSessionCache "shmcb:/var/run/ssl_scache(512000)"
SSLSessionCacheTimeout 300
SSLMutex "file:/var/run/ssl_mutex"

#Habilitando a trabalhar como virtualhost nas portas 80 e 443
NameVirtualHost *:80
NameVirtualHost *:443

#Redirecionamento o acesso a porta 80 para a 443
<VirtualHost *:80>
ServerName freebsd.douglasqsantos.com.br
Redirect / https://freebsd.douglasqsantos.com.br/
</VirtualHost>

#VirtualHost com https
<VirtualHost *:443>
  ServerAdmin webmaster@douglasqsantos.com.br
  ServerName freebsd.douglasqsantos.com.br
  ServerAlias freebsd.douglasqsantos.com.br
  DocumentRoot "/usr/local/docs/douglasqsantos.com.br"

#Controle de acesso ao diretorio do site
<Directory "/usr/local/docs/douglasqsantos.com.br">
  Options -Indexes +FollowSymLinks +MultiViews
  AllowOverride All
  Order Allow,Deny
  Allow from all
</Directory>

#Configuracao de Logs
  LogLevel warn
  CustomLog "/var/log/freebsd.douglasqsantos.com.br-access_log" combined
  ErrorLog "/var/log/freebsd.douglasqsantos.com.br-error_log"

#Configuracao de SSL
SSLEngine on
SSLProtocol all -SSLv2
SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5
SSLCertificateFile "/etc/ssl/apache/server.crt"
SSLCertificateKeyFile "/etc/ssl/apache/server.key"
<FilesMatch "\.(cgi|shtml|phtml|php)$">
    SSLOptions +StdEnvVars
</FilesMatch>
<Directory "/usr/local/www/apache22/cgi-bin">
    SSLOptions +StdEnvVars
</Directory>
#Tirando assinatura do servidor
ServerSignature Off
</VirtualHost>

Agora vamos criar o diretório para armazenar as chaves do ssl

mkdir /etc/ssl/apache

Agora vamos entrar no diretório para gerarmos a nossas chaves

cd /etc/ssl/apache

Agora vamos gerar a key do servidor

openssl genrsa -des3 -out server.key 2048
Generating RSA private key, 2048 bit long modulus
....................................+++
.......................+++
e is 65537 (0x10001)
Enter pass phrase for server.key:
Verifying - Enter pass phrase for server.key:

Agora precisamos gerar uma requisição de assinatura para o nosso certificado

openssl req -new -key server.key -out server.csr
Enter pass phrase for server.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AU]:BR
State or Province Name (full name) [Some-State]:Parana
Locality Name (eg, city) []:Curitiba
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Douglas
Organizational Unit Name (eg, section) []:TI
Common Name (eg, YOUR name) []:freebsd.douglasqsantos.com.br
Email Address []:douglas.q.santos@gmail.com

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:Douglas

Agora vamos auto-assinar o nosso certificado

openssl x509 -req -days 3650 -in server.csr -signkey server.key -out server.crt
Signature ok
subject=/C=BR/ST=Parana/L=Curitiba/O=Douglas/OU=TI/CN=freebsd.douglasqsantos.com.br/emailAddress=douglas.q.santos@gmail.com
Getting Private key
Enter pass phrase for server.key:

Agora vamos acertar a permissão dos certificados

chmod -R 0400 /etc/ssl/apache

Agora vamos acessar o diretório dos certificados

cd /etc/ssl/apache

Agora vamos fazer um backup da key

cp server.key server.key-orig

Agora vamos tirar a senha do certificado

openssl rsa -in server.key-orig -out server.key
Enter pass phrase for server.key-orig:
writing RSA key

Agora vamos mandar instalar o MySQL, escolha as opções padrões

cd /usr/ports/databases/mysql55-server && make install distclean

Nas dependências escolha as opções padrões

Após terminar a instalação vamos ter algo como abaixo

************************************************************************

Remember to run mysql_upgrade (with the optional --datadir=<dbdir> flag)
the first time you start the MySQL server after an upgrade from an
earlier version.

************************************************************************
install-info --quiet /usr/local/info/mysql.info /usr/local/info/dir
===> Correct pkg-plist sequence to create group(s) and user(s)
===>   Compressing manual pages for mysql-server-5.5.28
===>   Registering installation for mysql-server-5.5.28
===> SECURITY REPORT: 
      This port has installed the following files which may act as network
      servers and may therefore pose a remote security risk to the system.
/usr/local/libexec/mysqld

      This port has installed the following startup scripts which may cause
      these network services to be started at boot time.
/usr/local/etc/rc.d/mysql-server

      If there are vulnerabilities in these programs there may be a security
      risk to the system. FreeBSD makes no guarantee about the security of
      ports included in the Ports Collection. Please type 'make deinstall'
      to deinstall the port if this is a concern.

      For more information, and contact details about the security
      status of this software, see the following webpage: 
http://www.mysql.com/
===>  Cleaning for mysql-client-5.5.28
===>  Cleaning for mysql-server-5.5.28
===>  Deleting distfiles for mysql-server-5.5.28
make install distclean  557.94s user 99.16s system 69% cpu 15:51.17 total

Agora vamos colocar o apache e o MySQL na inicialização do sistema

vim /etc/rc.conf
[...]
apache22_enable="YES"
mysql_enable="YES"
mysql_dbdir="/var/db/mysql"

Agora vamos inicializar o MySQL

/usr/local/etc/rc.d/mysql-server start

Agora vamos setar uma senha para o root do MySQL

mysqladmin password 'senha' -u root

Agora vamos acertar o arquivo de configuração do MySQL

cp /usr/local/share/mysql/my-large.cnf /usr/local/etc/my.cnf
chmod 644 /usr/local/etc/my.cnf

Agora vamos liberar ele aceitar conexões fora o servidor local caso necessário caso seja efetuada somente conexões em localhost não precisamos modificar

vim /usr/local/etc/my.cnf
[...]
[mysqld]
bind-address    = 0.0.0.0

Agora vamos reiniciar o MySQL

/usr/local/etc/rc.d/mysql-server restart

Agora vamos criar o diretório que vai armazenar as nossas páginas

mkdir -p /usr/local/docs/douglasqsantos.com.br

Agora vamos acertar as permissões

chown -R www:www /usr/local/docs/douglasqsantos.com.br

Vamos criar um arquivo para testar o php

echo "<?php phpinfo(); ?>" > /usr/local/docs/douglasqsantos.com.br/phpinfo.php

Agora vamos criar um arquivo para testar o MySQL

vim /usr/local/docs/douglasqsantos.com.br/mysql.php
<?php
$link = mysql_connect('localhost', 'root', 'senha');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);
?>

Agora vamos testar a configuração do apache

apachectl configtest
Syntax OK

Caso tenha um aviso como abaixo

apachectl configtest
httpd: apr_sockaddr_info_get() failed for freebsd.douglasqsantos.com.br
httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName
Syntax OK

O cliente não está configurado corretamente o /etc/hosts então precisamos adicionar uma entrada da seguinte forma

vim /etc/hosts
[...]
ip_servidor    freebsd.douglasqsantos.com.br

Agora já podemos testar a configuração novamente

apachectl configtest
Syntax OK

Agora vamos inicializar o apache

apachectl start

Agora já podemos testar em:

Caso não tenha configurado o DNS ou o /etc/hosts do cliente precisamos acessar pelo endereço ip do servidor

Aqui eu estou direcionando todas as conexões do http para o https, caso ache necessário mude deixando a configuração da seguinte forma

vim /usr/local/etc/apache22/extra/httpd-vhosts.conf
#Habilitando escutar na porta 443 https
Listen 443

#Configuracoes do https
AddType application/x-x509-ca-cert .crt
AddType application/x-pkcs7-crl .crl
SSLPassPhraseDialog builtin
SSLSessionCache "shmcb:/var/run/ssl_scache(512000)"
SSLSessionCacheTimeout 300
SSLMutex "file:/var/run/ssl_mutex"

#Habilitando a trabalhar como virtualhost nas portas 80 e 443
NameVirtualHost *:80
NameVirtualHost *:443

#Acesso no virtualhost na porta 80 
<VirtualHost *:80>
  ServerAdmin webmaster@douglasqsantos.com.br
  ServerName freebsd.douglasqsantos.com.br
  ServerAlias freebsd.douglasqsantos.com.br
  DocumentRoot "/usr/local/docs/douglasqsantos.com.br"

#Controle de acesso ao diretorio do site
<Directory "/usr/local/docs/douglasqsantos.com.br">
  Options -Indexes +FollowSymLinks +MultiViews
  AllowOverride All
  Order Allow,Deny
  Allow from all
</Directory>

#Configuracao de Logs
  LogLevel warn
  CustomLog "/var/log/freebsd.douglasqsantos.com.br-access_log" combined
  ErrorLog "/var/log/freebsd.douglasqsantos.com.br-error_log"
#Tirando assinatura do servidor
ServerSignature Off
</VirtualHost>

#VirtualHost com https
<VirtualHost *:443>
  ServerAdmin webmaster@douglasqsantos.com.br
  ServerName freebsd.douglasqsantos.com.br
  ServerAlias freebsd.douglasqsantos.com.br
  DocumentRoot "/usr/local/docs/douglasqsantos.com.br"

#Controle de acesso ao diretorio do site
<Directory "/usr/local/docs/douglasqsantos.com.br">
  Options -Indexes +FollowSymLinks +MultiViews
  AllowOverride All
  Order Allow,Deny
  Allow from all
</Directory>

#Configuracao de Logs
  LogLevel warn
  CustomLog "/var/log/freebsd.douglasqsantos.com.br-access_log" combined
  ErrorLog "/var/log/freebsd.douglasqsantos.com.br-error_log"

#Configuracao de SSL
SSLEngine on
SSLProtocol all -SSLv2
SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5
SSLCertificateFile "/etc/ssl/apache/server.crt"
SSLCertificateKeyFile "/etc/ssl/apache/server.key"
<FilesMatch "\.(cgi|shtml|phtml|php)$">
    SSLOptions +StdEnvVars
</FilesMatch>
<Directory "/usr/local/www/apache22/cgi-bin">
    SSLOptions +StdEnvVars
</Directory>
#Tirando assinatura do servidor
ServerSignature Off
</VirtualHost>

Agora vamos testar a configuração do apache

apachectl configtest
Syntax OK

Agora vamos reiniciar o apache

apachectl restart

Agora já podemos utilizar o virtualhost na porta 80 ou com ssl na porta 443

Referências