This is Gentoo's testing wiki. It is a non-operational environment and its textual content is outdated.
Please visit our production wiki at https://wiki.gentoo.org
Apache/pt-br
The Apache HTTP Server is an efficient, extensible web server. It is one of the most popular web servers used the Internet.
Instalação
Ao atualizar uma versão do Apache, veja o Guia de Atualização.
USE flags
USE flags for www-servers/apache The Apache Web Server
+suexec-caps
|
Install suexec with capabilities instead of SUID |
debug
|
Enable extra debug codepaths, like asserts and extra output. If you want to get meaningful backtraces see https://wiki.gentoo.org/wiki/Project:Quality_Assurance/Backtraces |
doc
|
Add extra documentation (API, Javadoc, etc). It is recommended to enable per package instead of globally |
gdbm
|
Add support for sys-libs/gdbm (GNU database libraries) |
ldap
|
Add LDAP support (Lightweight Directory Access Protocol) |
selinux
|
!!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur |
ssl
|
Add support for SSL/TLS connections (Secure Socket Layer / Transport Layer Security) |
static
|
Link in apache2 modules statically rather then plugins |
suexec
|
Install suexec with apache |
suexec-syslog
|
Log suexec to syslog instead of to a separate file |
systemd
|
Enable use of systemd-specific libraries and features like socket activation or session tracking |
threads
|
Add threads support for various packages. Usually pthreads |
Emerge
If you want to use the Apache event MPM, then add the following to make.conf:
/etc/portage/make.conf
Apache event MPMAPACHE2_MPMS="event"
If you want to use the Apache worker MPM, then add the following to make.conf:
/etc/portage/make.conf
Apache worker MPMAPACHE2_MPMS="worker"
And, enable the Apache threads USE flag:
/etc/portage/package.use
Apache threads supportwww-servers/apache threads
Then emerge Apache:
root #
emerge --ask www-servers/apache
Suporte global
Habilitar a USE flag global apache2
fornece suporte ao Apache em outros pacotes. Isto deve fazer com que www-servers/apache seja instalado automaticamente se um pacote dependente do Apache foi instalado.
/etc/portage/make.conf
Adicionando o Apache às USE flags do sistemaUSE="apache2"
Após configurar as variáveis USE, atualize o sistema para que as mudanças tenham efeito:
root #
emerge --ask --changed-use --deep @world
Configuração
Arquivos
Há dois arquivos principais que configuram o comportamento do Apache2 no sistema:
- Arquivo de configuração do script de inicialização do Apache2 no Gentoo /etc/conf.d/apache2
- Arquivo convencional de configuração do servidor Apache2 /etc/apache2/httpd.conf
/etc/conf.d/apache2
O arquivo do apache2 em /etc/conf.d é o arquivo de configuração do script de inicialização do Gentoo. A única linha ativa neste arquivo é a linha da variável APACHE2_OPTS:
/etc/conf.d/apache2
APACHE2_OPTS="-D DEFAULT_VHOST -D INFO -D SSL -D SSL_DEFAULT_VHOST -D LANGUAGE"
Esta linha define opções que serão interpretadas por vários arquivos de configuração usando a expressão <IfDefine option-name>
para ativar ou desativar alguma parte da configuração toda. Isto será retornado mais tarde no artigo.
/etc/apache2/httpd.conf
O arquivo httpd.conf é o arquivo convencional de configuração do Apache. De fato este arquivo é apenas um ponto de entrada para a configuração. O arquivo todo é dividido em vários outros no diretório /etc/apache2/, os quais são reunidos usando a diretiva Include
. Por exemplo, a expressão Include /etc/apache2/modules.d/*.conf
, em httpd.conf, visa incluir todos os arquivos em /etc/apache2/modules.d/ cujo nome termine em .conf.
Levando em conta o que foi dito na subseção acima, e como arquivos de configuração de módulos (arquivos em /etc/apache2/modules.d) quase sempre começam com <IfDefine module-name>
, o conteúdo de um arquivo em /ect/apache2/modules.d, será anexado ao resto da configuração APENAS se a opção correspondente está definida usando uma flag -D module-name
na variável APACHE2_OPTS no arquivo /etc/conf.d/apache2. O arquivo de configuração 00_default_settings.conf é uma exceção à esta regra, já que ele não inicia com uma expressão IfDefine
e portanto é sempre incluído na configuração resultante.
Padrões
Após a instalação limpa de um servidor Apache, a configuração resultante da junção dos diferentes arquivos de configuração é como a seguir. Comece com o ponto de entrada /etc/apache2/httpd.conf.
Isto é dado apenas para referência rápida e uma visão geral. Usuários são fortemente convidados a revisar os comentários inclusos nos diversos arquivos para entender os prós e contras da configuração. Por favor confira também o manual do Apache para um entendimento mais profundo da configuração do servidor Apache.
/etc/apache2/httpd.conf
ServerRoot "/usr/lib64/apache2" #Module loaded unconditionally, assuming the USE flag is no unset in # /etc/portage/make.conf or in /etc/portage/package.use LoadModule actions_modulemodules/mod_actions.so ... #other modules loaded that way : alias_module, auth_basic_module, authn_alias_module, # authn_anon_module, authn_dbm_module, authn_default_module, authn_file_module, # authz_dbm_module, authz_default_module, authz_groupfile_module, authz_host_module, # authz_owner_module, authz_user_module, autoindex_module, cgi_module, cgid_module, # deflate_module, dir_module, env_module, expires_module, ext_filter_module, filter_module, # headers_module, include_module, log_config_module, logio_module, mime_module, # mime_magic_module, negotiation_module, rewrite_module, setenvif_module, # speling_module,ssl_module, status_module, unique_id_module, usertrack_module, host_alias_module #Modules loaded conditionally, assuming matching USE flag is not unset in # /etc/portage/make.conf or in /etc/portage/package.use (flag to be set in ) <IfDefine AUTHNZ_LDAP> LoadModule authnz_ldap_module modules/mod_authnz_ldap.so </IfDefine> #other modules loaded that way : cache_module, dav_module, dav_fs_module, # dav_lock_module,disk_cache_module, file_cache_module, info_module, ldap_module, # mem_cache_module, userdir_module User apache Group apache # Supplemental configuration #**************************************************************************************vvv #this part is included via Include /etc/apache2/modules.d/*.conf #included from /etc/apache2/modules.d/00_default_settings.conf-------------v #this is always included as there is not option to deactivate it. Timeout 300 KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 15 UseCanonicalName Off AccessFileName .htaccess ServerTokens Prod TraceEnable off ServerSignature On HostnameLookups Off EnableMMAP On EnableSendfile On FileEtag INode MTime Size ContentDigest Off ErrorLog /var/log/apache2/error_log LogLevel warn <Directory /> Options FollowSymLinks AllowOverride None Require all denied </Directory> <IfModule dir_module> DirectoryIndex index.html index.html.var </IfModule> <FilesMatch "^\.ht"> Require all denied </FilesMatch> #--------------------------------------------------------------------------^ #included from 00_mod_info.conf--------------------------------------------v <IfDefine INFO> <Location /server-info> SetHandler server-info Require host 127.0.0.1 </Location> </IfDefine> #--------------------------------------------------------------------------^ #--------------------------------------------------------------------------v #included from 00_languages.conf # Settings for hosting different languages. <IfDefine LANGUAGE> AddLanguage ca .ca ... AddLanguage zh-TW .zh-tw LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW ForceLanguagePriority Prefer Fallback AddCharset us-ascii.ascii .us-ascii AddCharset ISO-8859-1 .iso8859-1 .latin1 ... AddCharset shift_jis .shift_jis .sjis </IfDefine> #---------------------------------------------------------------------------^ #**************************************************************************************^^^ #***************************************************************************************vvv #this part is included via Include /etc/apache2/vhosts.d/*.conf #from 00_default_ssl_vhost.conf-----------------------------------------------------vv <IfDefine SSL> <IfDefine SSL_DEFAULT_VHOST> <IfModule ssl_module> Listen 443 <VirtualHost _default_:443> ServerName localhost #------------------------------------------v # this part is included via Include /etc/apache2/vhosts.d/default_vhost.include ServerAdmin root@localhost DocumentRoot "/var/www/localhost/htdocs" <Directory "/var/www/localhost/htdocs"> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> <IfModule alias_module> ScriptAlias /cgi-bin/ "/var/www/localhost/cgi-bin/" </IfModule> <Directory "/var/www/localhost/cgi-bin"> AllowOverride None Options None Require all granted </Directory> #end of Include ---------------------------^ ErrorLog /var/log/apache2/ssl_error_log <IfModule log_config_module> TransferLog /var/log/apache2/ssl_access_log </IfModule> SSLEngine on SSLCipherSuite ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP:+eNULL SSLCertificateFile /etc/ssl/apache2/server.crt SSLCertificateKeyFile /etc/ssl/apache2/server.key <FilesMatch "\.(cgi|shtml|phtml|php)$"> SSLOptions +StdEnvVars </FilesMatch> <Directory "/var/www/localhost/cgi-bin"> SSLOptions +StdEnvVars </Directory> <IfModule setenvif_module> BrowserMatch ".*MSIE.*" \ nokeepalive ssl-unclean-shutdown \ downgrade-1.0 force-response-1.0 </IfModule> <IfModule log_config_module> CustomLog /var/log/apache2/ssl_request_log \ "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b" </IfModule> </VirtualHost> </IfModule> </IfDefine> </IfDefine> #---------------------------------------------------------------------------------^^ #from 00_default_vhost.conf-------------------------------------------------------vv <IfDefine DEFAULT_VHOST> Listen 80 NameVirtualHost *:80 <VirtualHost *:80> ServerName localhost #---------------------------------------------------------------v # this part is included via Include /etc/apache2/vhosts.d/default_vhost.include ServerAdmin root@localhost DocumentRoot "/var/www/localhost/htdocs" <Directory "/var/www/localhost/htdocs"> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> <IfModule alias_module> ScriptAlias /cgi-bin/ "/var/www/localhost/cgi-bin/" </IfModule> <Directory "/var/www/localhost/cgi-bin"> AllowOverride None Options None Require all granted </Directory> #end of Include -----------------------------------------------^ <IfModule mpm_peruser_module> ServerEnvironment apache apache </IfModule> </VirtualHost> </IfDefine> #-----------------------------------------------------------------------------------^^ # end of include ****************************************************************************************^^^
Primeiro sinal de vida
Como visto na configuração inicial acima, o diretório do DocumentRoot
do host virtual pré-instalado é /var/www/localhost/htdocs e seu nome de servidor é localhost. Além disso um arquivo index.html é fornecido na pasta DocumentRoot
, sendo assim, para checarmos se tudo está corretamente instalado ou não, aponte um navegador para http://localhost/.
Uma mensagem de "It works!" deve ser exibida na página.
Fora da caixa, Firefox possui uma funcionalidade desenhada para ajudar os usuários que comumente erram URL's na barra de endereços. Se uma URL falha na resolução, o Firefox tenta algumas alterações da URL para encontrar o que o usuário 'quis dizer' de fato, anexando um
.com
ou prefixando um www.
à URL para ver se isso resolve.
Esta funcionalidade, a qual foi introduzida nas primeiras versões do Firefox, é um tanto chata para desenvolvedores. Ela significa que quando um servidor rodando no localhost falha ao responder, o Firefox decide tentar localhost.com
ou www.localhost.com
. Isto frequentemente resulta em um erro 404.
Para desabilitar esta funcionalidade:
- Digite
about:config
na barra de endereços e pressionte Enter - Clique em "Serei cuidadoso, prometo!" (ou "I'll be careful") e entre na página de configurações especiais
- Digite
browser.fixup.alternate.enabled
na bara de pesquisa e pressione Enter - Clique com o botão direito em
browser.fixup.alternate.enabled
e mude seu valor para false.
Habilitando mod_security
Instale www-apache/mod_security:
root #
emerge --ask www-apache/mod_security
Habilite o módulo SECURITY
na variável APACHE2_OPTS do arquivo apache2:
/etc/conf.d/apache2
Habilitando o módulo de segurançaAPACHE2_OPTS="... -D SECURITY"
Controle este módulo editando os arquivos /etc/apache2/modules.d/79_modsecurity.conf e /etc/apache2/modules.d/80_modsecurity-crs.conf, e então reinicie o Apache.
Habilitando suporte a PHP
Instale o PHP com a USE flag apache2
e habilite o módulo:
With >=app-eselect/eselect-php-0.8.1, the APACHE2_OPTS variable changed to
-D PHP
instead of -D PHP5
. This allows for future major versions to flow smoothly. As of eselect-php-0.9.4-r5, the compatibility shim was dropped after allowing 2 years to convert./etc/conf.d/apache2
Habilitando o módulo PHPAPACHE2_OPTS="... -D PHP"
Antes de testar se o módulo PHP funciona, verifique se o arquivo /etc/apache2/modules.d/70_mod_php.conf existe e contém a seguinte definição:
/etc/apache2/modules.d/70_mod_php.conf
Verificando se o módulo PHP será carregado<IfDefine PHP> # The mod_php.so symlink is controlled by # eselect-php. However, the module name changed from # php5_module to php7_module so we can't blindly load whatever # is there. Instead we let eselect-php manage a small # configuration file that loads the appropriate module. # # This is relative to ServerRoot (see httpd.conf). Include ../../../var/lib/eselect-php/mod_php.conf # Tell apache that mod_php should handle PHP files. # # NOTE: Avoiding AddHandler/AddType for security (bug # #538822). Please read the related news item! <FilesMatch "\.(php|php[57]|phtml)$"> SetHandler application/x-httpd-php </FilesMatch> # PHP source files which are meant to be displayed as # syntax-highlighted source code. <FilesMatch "\.phps$"> SetHandler application/x-httpd-php-source </FilesMatch> DirectoryIndex index.php index.phtml </IfDefine>
Se ele não existir, crie-o.
Para verificar se o módulo PHP funciona, crie uma página de teste:
/var/www/localhost/htdocs/index.php
PHP test page<html> <body> <?php phpinfo(); ?> </body> </html>
Agora, omita ou renomeie /var/www/localhost/htdocs/index.html e abra a página de teste: http://localhost/
Uma tabela descrevendo as configurações do PHP deve estar visível.
Modificar versões do PHP
Para alterar a versão do PHP manipulada pelo Apache, primeiro liste as versões disponíveis para a interface SAPI (Server Application Programming Interface) do apache2
:
root #
eselect php list apache2
[1] php5.3 [2] php5.4 * [3] php5.5
Altere para a versão de sua escolha:
root #
eselect php set apache2 N
Substitua N
no exemplo acima pelo número solicitado na saída do comando eselect php list apache2 como exibido anteriormente.
Hosts virtuais
Para cada host virtual, forneça um diretório DocumentRoot
alcançável e acessível pelo daemon do Apache. Adicione um arquivo de configuração de host vitual (VirtualHost.conf) na pasta /etc/apache2/vhosts.d, a qual usa este DocumentRoot
e o nome de servidor do host virtual. Não esqueça de adicionar uma entrada para este nome de domínio em /etc/hosts.
Para atribuir a propriedade de usuário/grupo para o apache nos arquivos de host virtuais, use chown como no exemplo a seguir:
root #
chown apache:apache /var/www/sitename
Abaixo estão dois exemplos de definição de host virtual, uma para domainname1.com e outra para domainname2.com. Repare as diferentes diretivas de DocumentRoot
e ServerName
mesmo que o host em si (*:80
) permaneça o mesmo:
<VirtualHost *:80> ServerAdmin email@site.com DocumentRoot /var/www/website1 ServerName domainname1.com </VirtualHost> <VirtualHost *:80> ServerAdmin email@site.com DocumentRoot /var/www/website2 ServerName domainname2.com </VirtualHost>
É recomendado fornecer uma definição host virtual baseado em IP também. Isto permite ao administrador colocar uma mensagem aos usuários que tentarem acessar um site neste endereço IP:
<VirtualHost *:80> ServerAdmin email@site.com DocumentRoot /var/www/html ServerName xxx.xxx.xxx.xxx </VirtualHost>
Após inserir os hosts virtuais, o servidor precisa ser (graciosamente) reiniciado para os novos sites se tornarem ativos.
Habilitando PHP por fcgid
Instale www-apache/mod_fcgid e dev-lang/php. O pacote PHP requer a USE flag cgi
definida:
root #
emerge --ask www-apache/mod_fcgid dev-lang/php
Edite o arquivo mod_fcgid.conf:
/etc/apache2/modules.d/20_mod_fcgid.conf
<IfDefine FCGID> LoadModule fcgid_module modules/mod_fcgid.so SocketPath /var/run/fcgidsock SharememPath /var/run/fcgid_shm AddHandler php-fcgid .php AddType application/x-httpd-php .php Action php-fcgid /fcgid-bin/php-fcgid-wrapper # max request 128mb FcgidMaxRequestLen 134217728 <Location /fcgid-bin/> SetHandler fcgid-script Options +ExecCGI </Location> </IfDefine>
Crie a pasta necessária:
root #
mkdir /var/www/localhost/htdocs/fcgid-bin
Crie um link simbólico para o wrapper do PHP:
root #
ln -s /usr/bin/php-cgi /var/www/localhost/htdocs/fcgid-bin/php-fcgid-wrapper
Habilite o módulo fcgid
:
/etc/conf.d/apache2
Habilitando o módulo fcgidAPACHE2_OPTS="... -D FCGID"
Por fim reinicie o Apache e verifique o site phpinfo()
criado anteriormente. O valor de Server API
deve ser CGI/FastCGI
Habilitando PHP-FPM pelo mod_proxy_fcgi no Apache 2.4
Os seguintes pré-requisitos devem ser cumpridos para permitir PHP-FPM através do mod_proxy_fcgi:
- >= PHP 5.3
- >= Apache 2.4
Furthermore, there are a few restrictions on the availability of functionality within Apache 2.4:
- >= Apache 2.4.9, if you want to communicate with PHP-FPM over UNIX sockets
- >= Apache 2.4.10, if you want to use SetHandler instead of ProxyPassMatch.
A seguinte configuração só funciona com o Apache 2.4.10 e mais recentes. Baseia-se na diretiva FilesMatch
e será colocado dentro da principal configuração ou VirtualHosts
. A localização do socket UNIX é determinada pela diretiva listen
no arquivo de configuração php-fpm.conf, permitindo especificar grupos separados por local ou função.
No exemplo a seguir, FilesMatch
é colocado dentro do arquivo de módulo de configuração do PHP module do Apache:
/etc/apache2/modules.d/70_mod_php.conf
Usando PHP-FPM (recomendado para Apache 2.4.10 e mais recentes)<IfDefine PHP> <FilesMatch "\.php$"> SetHandler "proxy:unix:/var/run/php-fpm/www.sock|fcgi://localhost" </FilesMatch> # Set it to handle the files <IfModule mod_mime.c> AddHandler application/x-httpd-php .php .php5 .phtml AddHandler application/x-httpd-php-source .phps </IfModule> DirectoryIndex index.php index.phtml </IfDefine>
Or, you can use ProxPassMatch -- the only option if the Apache version is between 2.4.0 and 2.4.8, inclusive.
/etc/apache2/modules.d/70_mod_php.conf
Using PHP-FPM (recommended for Apache 2.4.8 and older)<IfDefine PHP> # Send all requested PHP files to PHP-FPM via fcgi://PHP_FPM_LISTEN_ADDRESS:PHP_FPM_LISTEN_PORT/DOCUMENT_ROOT/$1 ProxyPassMatch ^/(.*\.php)$ fcgi://127.0.0.1:9000/var/www/localhost/htdocs/$1 # Set it to handle the files <IfModule mod_mime.c> AddHandler application/x-httpd-php .php .php5 .phtml AddHandler application/x-httpd-php-source .phps </IfModule> DirectoryIndex index.php index.phtml </IfDefine>
Por padrão a diretiva listen
não é definida para um socket. Primeiro crie o diretório para o arquivo de socket:
root #
mkdir /var/run/php-fpm
Depois, atualize o arquivo php-fpm.conf como a seguir:
php-fpm.conf
Atualizando a diretiva listen; Set permissions for unix socket, if one is used. In Linux, read/write ; permissions must be set in order to allow connections from a web server. Many ; BSD-derived systems allow connections regardless of permissions. ; Default Values: user and group are set as the running user ; mode is set to 0666 listen.owner = nobody listen.group = nobody ;listen.mode = 0666 ; The address on which to accept FastCGI requests. ; Valid syntaxes are: ; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific address on ; a specific port; ; 'port' - to listen on a TCP socket to all addresses on a ; specific port; ; '/path/to/unix/socket' - to listen on a unix socket. ; Note: This value is mandatory. ;listen = 127.0.0.1:9000 listen = /var/run/php-fpm/www.sock
Então habilite o módulo tanto do PHP
quanto o de PROXY
:
/etc/conf.d/apache2
Habilitando os módulos do PHP e proxyAPACHE2_OPTS="... -D PHP -D PROXY"
Uso
Serviços
OpenRC
Inicie o servidor Apache:
root #
/etc/init.d/apache2 start
Adicione o Apache ao runlevel padrão:
root #
rc-update add apache2 default
Reinicie o serviço do Apache:
root #
/etc/init.d/apache2 restart
Recarregue os arquivos de configuração do Apache:
root #
/etc/init.d/apache2 reload
systemd
Inicie o servidor do Apache:
root #
systemctl start apache2
Adicione o Apache ao runlevel padrão:
root #
systemctl enable apache2
Reinicie o serviço do Apache:
root #
systemctl restart apache2
Resolução de problemas
Recursos
O servidor Apache pode ser difícil de configurar corretamente. Abaixo estão alguns recursos que podem ser úteis quando isso ocorrer:
Teste
Verificando as interfaces IP e portar onde o Apache2 está rodando e ouvindo:
root #
netstat -tulpen | grep apache
tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 0 10932720 4544/apache2 tcp 0 0 0.0.0.0:443 0.0.0.0:* LISTEN 0 10932716 4544/apache2
Testando se uma conexão com o servidor Apache está funcionando no localhost:
user $
telnet localhost 80
Trying 127.0.0.1... Connected to localhost. Escape character is '^]'.
Interrompa o teste de conexão pressionando Ctrl+c e Enter.
apr_sockaddr_info_get() failed for <System_Hostname>
Error:
apache2: apr_sockaddr_info_get() failed for System_Hostname
Resolution:
Quando isto ocorrer, adicione o nome do host ao arquivo /etc/hosts:
/etc/hosts
Adicionando um nome de host para o Apache127.0.0.1 localhost System_Hostname
Veja também
- Lighttpd — a fast and lightweight web server.
- Nginx — a robust, small, high performance web server and reverse proxy server.
Recursos externos
- Slicehost article: Installing Apache on Gentoo
- Slicehost article: Apache configuration files on Gentoo
- Slicehost article: Configuring the Apache MPM on Gentoo
- Slicehost article: Apache configuration on Gentoo
- Slicehost article: Apache Virtual Hosts on Gentoo
- Slicehost article: Enabling and using apache's mod_status on Gentoo
- apache.org documentation
- Apache2 mod_pagespeed