Apache

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page Apache and the translation is 87% complete.
Outdated translations are marked like this.

El Servidor HTTP Apache es un servidor Web eficiente y extensible. Es uno de los servidores Web más populares usados en Internet.

Instalación

Nota
Cuando actualizamos entre versiones de Apache, Valide el Guía de actualización.

Ajustes USE

USE flags for www-servers/apache The Apache Web Server

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
split-usr Enable behavior to support maintaining /bin, /lib*, /sbin and /usr/sbin separately from /usr/bin and /usr/lib*
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-caps Install suexec with capabilities instead of SUID
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

Módulo de multi-procesamiento

Si se quiere utilizar el Apache event o el worker MPM, habilite el ajuste USE threads:

ARCHIVO /etc/portage/package.useSoporte para hilos de ejecución en Apache
www-servers/apache threads
ARCHIVO /etc/portage/package.useApache threads support
www-servers/apache threads

Si quiere utilizar Apache event MPM, entonces añada lo siguiente a make.conf:

ARCHIVO /etc/portage/make.confApache event MPM
APACHE2_MPMS="event"
ARCHIVO /etc/portage/make.confApache event MPM
APACHE2_MPMS="event"

Si quiere utilizar Apache worker MPM, entonces añada lo siguiente a make.conf:

ARCHIVO /etc/portage/make.confApache worker MPM
APACHE2_MPMS="worker"
ARCHIVO /etc/portage/make.confApache worker MPM
APACHE2_MPMS="worker"

Si no se ha seleccionado ningún Módulo de Multiproceso (MPM), se utilizará el módulo MPM por defecto. El módulo MPM por defecto depende de las capacidades de la plataforma (como por ejemplo el soporte para la ejecución de hilos), lea más sobre esto en los documentos oficiales de Apache.

A continuación haga emerge de Apache:

root #emerge --ask www-servers/apache
root #emerge --ask www-servers/apache

Soporte global =

Agregando apache2 dentro de los parámetros USE globales se proveerá soporte para Apache en otros paquetes. Esto puede causar que www-servers/apache sea instalado automáticamente si un paquete que dependa de este es emergido.

ARCHIVO /etc/portage/make.confAgregar Apache a los ajustes USE del sistema
USE="apache2"

Después de configurar los parámetros USE, actualiza el sistema para que los cambios tengan efecto:

root #emerge --ask --changed-use --deep @world

Configuración

Ficheros

Hay dos archivos principales que configuran el comportamiento de Apache2 en el sistema:

  • Archivo de guión de inicio de Apache2 sobre Gentoo /etc/conf.d/apache2
  • Archivo de configuración convencional de Apache2 /etc/apache2/httpd.conf

/etc/conf.d/apache2

El archivo apache2 ubicado en /etc/conf.d es el guión de inicio de Gentoo. La única linea activa en este archivo es la de la variable APACHE2_OPTS:

ARCHIVO /etc/conf.d/apache2
APACHE2_OPTS="-D DEFAULT_VHOST -D INFO -D SSL -D SSL_DEFAULT_VHOST -D LANGUAGE"

Esta linea define la opciones que serán interpretadas por varios archivos de configuración usando usando la declaración <ifDefine option-name> para activar o desactivar alguna parte de la configuración. Esto será retomado más tarde en el articulo.

/etc/apache2/httpd.conf

El archivo httpd.conf es el convencional de apache. En efecto este archivo es solo un "punto de entrada" para la configuración. Toda la configuración está separada en muchos archivos dentro del directorio /etc/apache2/, que se ensamblan entre sí usando la directiva include. Por ejemplo, la entrada Include /etc/apache2/modules.d/*.conf, en httpd.conf, tiene como objetivo incluir todos los archivos en /etc/apache2/modules.d/ cuyo nombre termine con .conf.

Teniendo en cuenta lo dicho en el párrafo anterior, y como los archivos de configuración de módulos (archivos en /etc/apache2/modules.d) a menudo inician con <IfDefine module-name>, el contenido de un archivo dentro /ect/apache2/modules.d, sería SOLO ensamblado con el resto de la configuración si la opción correspondiente se ajusta mediante un parámetro -D module-name en la variables APACHE2_OPTS dentro del archivo /etc/conf.d/apache2. El archivo de configuración 00_default_settings.conf es una excepción a esta regla como no inicia con la declaración IfDefine y por lo tanto, siempre se incluye en la configuración resultante.

Valores por defecto

Después de una nueva instalación de un servidor Apache, la configuración resultante del conjunto de los diferentes archivos de configuración es el siguiente. Inicia con un punto de entrada /etc/apache2/httpd.conf.

Advertencia
Este es "solo" dado para referencia rápida y para dar una vista completa. Los usuarios están invitados fuertemente a revisar los comentarios incluidos en los diferentes archivos para entender los pros y contras de la configuración. Por favor además dirígete al manual de Apache para un entendimiento profundo de la configuración de Apache.
ARCHIVO /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 ****************************************************************************************^^^

Primera señal de vida

Como es visible en la configuración inicial , el directorio del virtual host pre instalado DocumentRoot es /var/www/localhost/htdocs, su nombre de servicio es "localhost". En adición un archivo index.html es provisto en el directorio DocumentRoot, por tanto, para comprobar si todo está instalado o no correctamente, apunta un navegador a https://localhost/.

Un mensaje "It Works!" debe aparecer en la página.

Advertencia
Out of the box, Firefox tiene una característica designada para ayudar a los usuarios que escriben incorrectamente la URL en la barra de navegación. Si se falla en resolver la URL, Firefox intenta un par de alternativas para intentar encontrar lo que el usuario "realmente quería" como destino. Agregando un .com o prefijando un www al hostname especificado para ver si así resuelve.

Esta característica, que se introdujo en las primeras versiones de Firefox es algo molesto para los desarrolladores. La característica significa que cuando falla un servidor que ejecuta en el servidor local para responder, Firefox decidirá intentar localhost.com o www.localhost.com. Esto a menudo resolverá una página no encontrada.

Para desabilitar esta característica:

  1. Ingresa about:config en la barra del navegador
  2. Click "I'll be careful" e ingresar a la página de configuración especial
  3. Ingresar browser.fixup.alternate.enabled en la caja de búsqueda que aparece
  4. Click derecho sobre browser.fixup.alternate.enabled que aparece en la lista filtrada that appears in the filtered lista de abajo y elegir de palanca para ajustar el valor en false.

Habilitando mod_security

ModSecurity es una aplicación web cortafuegos basado en reglas que monitoriza el tráfico del servicio web con el fin de bloquear ataques que exploten vulnerabilidades conocidas.

Instalar www-apache/mod_security:

root #emerge --ask www-apache/mod_security

Habilitar el módulo SECURITY en la variable APACHE2_OPTS del fichero apache2:

ARCHIVO /etc/conf.d/apache2Habilitando el módulo de seguridad
APACHE2_OPTS="... -D SECURITY"

Controlar este módulo editando los archivos /etc/apache2/modules.d/79_modsecurity.conf y /etc/apache2/modules.d/80_modsecurity-crs.conf. El archivo /usr/share/doc/mod_security-*/modsecurity.conf-recommended.bz2 contiene la configuración recomendada https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual#A_Recommended_Base_Configuration. Copies esta configuración básica a /etc/apache2/modules.d/79_modsecurity.conf y modifique los ajustes para que se adapten a sus necesidadaes. Desempaquete el fichero /usr/share/doc/modsecurity-crs-*/crs-setup.conf.example.bz2 a una localización adecuada, por ejemplo /etc/conf.d/crs-setup.conf, modifíquelo e incluya el fichero desempaquetad en /etc/apache2/modules.d/80_modsecurity-crs.conf. Para terminar, reinicie Apache. Busque errrores en los ficheros de registro de Apache de sus sitios y actúe convenientemente.

Habilitando soporte PHP

Instala PHP con el parámetro USE apache2 y habilita el módulo:

ARCHIVO /etc/conf.d/apache2Habilitar el módulo de PHP
APACHE2_OPTS="... -D PHP"

Antes de probar si el módulo PHP trabaja, valida que el archivo /etc/apache2/modules.d/70_mod_php.conf exista y contenta la siguiente definición:

ARCHIVO /etc/apache2/modules.d/70_mod_php.confVerificar que se cargará el módulo de PHP
<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>

Si no existe crealo.

Para verificar que el módulo PHP trabaje, create una página de prueba:

ARCHIVO /var/www/localhost/htdocs/index.phpPágina de prueba de PHP
<html>
 <body>
  <?php phpinfo(); ?>
 </body>
</html>

Ahora, suprime o renombra /var/www/localhost/htdocs/index.html y abre la página de prueba: https://localhost/

Una tabla describiendo las configuraciones de PHP debería ser vista.

Modificar las versiones de PHP

Para cambiar la versión de PHP que gestiona Apache, en primer lugar se deben listar las versiones disponibles del Server Application Programming Interface (SAPI) de apache2:

root #eselect php list apache2
 [1]   php5.3
 [2]   php5.4 *
 [3]   php5.5

Cambiar a la versión deseada:

root #eselect php set apache2 N

Sustituir N en el ejemplo de arriba por el número requerido en la salida de eselect php list apache2 tal y como se ha mostrado.

Host Virtuales =

Para cada host virtual, provee un directorio DocumentRoot que sea legible y accesible por el demonio Apache. Agrega un host virtual al archivo de configuración (VirtualHost.conf) en el directorio /etc/apache2/vhosts.d que use este DocumentRoot y el nombre del servicio del virtual host. No olvides agregar una entrada para este nombre de dominio en /etc/hosts.

Para asignar a un usuario/grupo de apache sea propietario de los archivos del host virtual, usa chown como en el siguiente ejemplo:

root #chown apache:apache /var/www/sitename

A continuación se presentan dos ejemplos de definiciones de host virtuales, uno para domainname1.com y otro para domainname2.com. Note los diferentes DocumentRoot y ServerName aunque la directiva de host por si mismo sigue siendo el mismo (*:80)

CÓDIGO Ejemplo de definiciones de host virtuales
<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>

Se recomienda dar una definición de host virtual basado en la IP también. Esto permite al administrador poner un mensaje para los usuarios que tratan de llegar a un sitio a través de su dirección IP:

CÓDIGO Host virtual basado en IP
<VirtualHost *:80>
    ServerAdmin email@site.com
    DocumentRoot /var/www/html
    ServerName xxx.xxx.xxx.xxx
</VirtualHost>

Después de insertar los virtual host, el servidor necesita ser (satisfactoriamente) reiniciado para que el nuevo sitio se active.

Habilitando PHP mediante fcgid

Instala www-apache/mod_fcgid y dev-lang/php. El paquete PHP requiere cgi como parámetro USE:

root #emerge --ask www-apache/mod_fcgid dev-lang/php

Edit the mod_fcgid.conf file:

ARCHIVO /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>

Crea el directorio necesario:

root #mkdir /var/www/localhost/htdocs/fcgid-bin

Enlace simbólico para la envoltura de PHP:

root #ln -s /usr/bin/php-cgi /var/www/localhost/htdocs/fcgid-bin/php-fcgid-wrapper

Habilitar el módulo FCGID:

ARCHIVO /etc/conf.d/apache2Habilitando el módulo fcgid
APACHE2_OPTS="... -D FCGID"

Finalmente reinicia Apache y valida el sitio con phpinfo() creado previamente. El valor de Servidor API debería ser "CGI/FastCGI"

Habilitando PHP-FPM a través de mod_proxy_fcgi en apache 2.4

Los siguientes prerequisitos se deben satisfacer para habilitar PHP-FPM a través de mod_proxy_fcgi:

  • >= PHP 5.3
  • >= Apache 2.4

Aún más, hay pocas restricciones en la disponibilidad y funcionalidad en Apache 2.4:

La siguiente configuración funcionará únicamente con Apache 2.4.10 y posteriores. Se apoya en la directiva FilesMatch y se coloca dentro de la configuración del servidor principal o en VirtualHosts. La ubicación de los zócalos de UNIX se determina en la directiva listen en el archivo de configuración php-fpm.conf, permitiendo la especificación para grupos separados por sitio o función.

En el siguiente ejemplo, se escribe FilesMatch en el archivo de configuración del módulo PHP de Apache:

ARCHIVO /etc/apache2/modules.d/70_mod_php.confUtilizar PHP-FPM (recomendado para Apache 2.4.10 y posteriores)
<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>

O se puede utilizar ProxPassMatch, la única opción si al versión de Apache está entre la 2.4.0 y la 2.4.8 (inclusives).

ARCHIVO /etc/apache2/modules.d/70_mod_php.confUtilizar PHP-FPM (recomendado para Apache 2.4.8 y posteriores)
<IfDefine PHP>
        # Enviar todos los ficheros PHP solicitados a PHP-FPM a través de  fcgi://DIRECCIÓN_DE_ESCUCHA_DE_PHP_FPM:PUERTO_DE_ESCUCHA_DE_PHP_FPM/RAÍZ_DE_DOCUMENTOS/$1
        ProxyPassMatch ^/(.*\.php)$ fcgi://127.0.0.1:9000/var/www/localhost/htdocs/$1
  
	# Configurarlo para gestionar los ficheros
	<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 defecto la directiva listen no es establecida para un socket. Primero crea el directorio para el archivo del socket:

root #mkdir /var/run/php-fpm

Siguiente, actualiza el archivo php-fpm.conf como sigue:

ARCHIVO php-fpm.confActualizar la directiva 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 = apache
listen.group = apache
;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

A continuación habilitar los módulos PHP y PROXY:

ARCHIVO /etc/conf.d/apache2Habilitando los módulos proxy y PHP
APACHE2_OPTS="... -D PHP -D PROXY"

Marcos de trabajo (frameworks) Web y Apache

Algunos de los marcos de trabajo que pueden trabajar con Apache, se cubren en el wiki:

HTTPS con certificados TLS de Let's Encrypt

Es importante que cualquier see.rvidor web que se ofrece al público ofrezca acceso HTTPS "seguro". A menudo, los sitios que ofrecen HTTPS se configuran para redirigir las peticiones HTTP al URL HTTPS equivalente.

Let’s Encrypt es una autoridad certificadora sin ánimo de lucro que ofrece certificados TLS gratuitos. certbot es una utilidad disponible en el repositorio de Gentoo para solicitar e instalar fácilmente certificados TLS, y configurar automáticamente el acceso HTTPS para Apache.

Lea el artículo sobre Let’s Encrypt para obtener información acerca de cómo usar certbot. La fundación EFF también ofrece instrucciones específicas sobre cómo usar certbot en Gentoo para configurar Apache.

Usos

Servicios

OpenRC

Inicia el servicio Apache:

root #/etc/init.d/apache2 start

Agregue Apache al guión de inicio por defecto:

root #rc-update add apache2 default

Reinicia el servicio de Apache:

root #/etc/init.d/apache2 restart

Recarga los archivos de configuración de Apache:

root #/etc/init.d/apache2 reload

systemd

Inicia el servicio de Apache:

root #systemctl start apache2

Agrega Apache al guión de inicio por defecto:

root #systemctl enable apache2

Reinicia el servicio de Apache:

root #systemctl restart apache2

Solución de problemas

Recursos

El servicio de Apache puede ser difícil para configurar apropiadamente. A continuación se presentan algunos recursos que pueden ser útiles cuando se producen problemas

Evaluando

Verificando las IP, interfaces y puertos con que Apache está corriendo y escuchando:

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        

Probando si una conexión a un servicio Apache está trabajando sobre localhost:

user $telnet localhost 80
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.

Interrumpe la prueba de conexión con Ctrl+c y Enter.

apr_sockaddr_info_get() failed for <System_Hostname>

Error:

apache2: apr_sockaddr_info_get() failed for System_Hostname

Resolución:

Cuando esto ocurre, agrega el nombre del host al archivo /etc/hosts:

ARCHIVO /etc/hostsAgregando un nombre de Host a Apache
127.0.0.1 localhost System_Hostname

Ver también

Recursos externos