Apache

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

Apache HTTP Server 是一个高效的可扩展的web 服务器。 它是当前因特网上使用最为普遍的 web 服务器之一。

安装

附注
如果是升级 Apache 新版本,请查看 Upgrade guide.

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

安装

多进程模块

如果要使用 Apache 事件或工作 MPM,请启用 Apache 线程 USE 标记:

文件 /etc/portage/package.useApache 线程支持
www-servers/apache threads
文件 /etc/portage/package.useApache threads support
www-servers/apache threads

如果你要使用 Apache event MPM 模式, 把下面的内容添加到 make.conf 里面:

文件 /etc/portage/make.confApache event MPM
APACHE2_MPMS="event"
文件 /etc/portage/make.confApache event MPM
APACHE2_MPMS="event"

如果你要使用 Apach worker MPM 模式, 把下面的内容添加到 make.conf 里面:

文件 /etc/portage/make.confApache worker MPM
APACHE2_MPMS="worker"
文件 /etc/portage/make.confApache worker MPM
APACHE2_MPMS="worker"

如果未选择多处理模块 (MPM),则使用默认 MPM。 默认 MPM 取决于平台功能(如线程支持), 在 Apache 官方文档阅读更多内容。

然后我们安装Apache:

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

Global USE 支持

开启apache2 global USE 标记可以给Apache多提供一些其他的软件包。 可能在安装www-servers/apache时,如果Apache依赖其他软件时,他们就会被安装。

文件 /etc/portage/make.conf添加 Apache 到系统 USE 标记
USE="apache2"

配置USE变量以后,更新系统来使得某些配置生效。

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

配置

文件

在系统里,Apache2有两个主要的配置文件:

  • Gentoo 的 Apache2 初始化配置文件 /etc/conf.d/apache2
  • Apache2 服务器的常规配置文件

/etc/apache2/httpd.conf

/etc/conf.d/apache2

apache2 位于 /etc/conf.d ,他是 Gentoo 初始化脚步配置的文件。唯一生效的一行是APACHE2_OPTS :

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

这个定义将解释使用<IfDefine option-name>语句激活或停用整个配置的各种配置文件某些部分的选项。下文将详细介绍。

/etc/apache2/httpd.conf

httpd.conf文件是Apache服务器的常规配置文件。 实际上这个文件只是一个入口点的配置。 完全的配置分散在/ etc / apache2 /目录中的许多文件中,使用Include指令组合在一起。 例如,httpd.conf中的语句Include /etc/apache2/modules.d/*.conf旨在将所有包含在/apache2/modules.d/文件夹中的文件组合起来,其文件名以 .conf结尾。

考虑到上面小节中的描述,如果选项使用位于 /etc/conf.d/apache2 文件中的 APACHE2_OPTS </ var> 变量的 -D module-name 标记。那么作为模块配置文件 ( /etc/apache2/modules.d) 几乎总是以<IfDefine module-name>,在/ect/apache2/modules.d中的一个文件的内容,与其余部分的配置组合。00_default_settings.conf 配置文件是此规则的例外,因为它不以IfDefine语句开头,因此始终包含在生成的配置中。

默认值

在全新安装Apache服务器之后,由不同配置文件的集合生成的配置如下。 从入口点/etc/apache2/httpd.conf开始。

警告
这是“只有”给出快速参考和给出一个总体看法。 强烈请求您查看各种文件中包含的注释,以了解配置中的内容。 还请参阅Apache手册以深入了解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 ****************************************************************************************^^^

新的开始

在上面的初始配置中可以看到,安装的虚拟主机的DocumentRoot目录是/var/www/localhost/htdocs,其服务器名称是“localhost”。 此外,在DocumentRoot目录中提供了一个index.html文件,以检查一切是否正确安装,打开浏览器访问http://localhost/

"It works!"的字样应该被打印到您的屏幕上。
警告
Firefox开箱即用的功能旨在帮助那些在浏览器栏中输入错误的网址的用户。 如果网址无法解析,Firefox会尝试对网址进行一些更改,以尝试找到用户可能想要的内容,附加一个 .com 或加上 www. 到URL的主机名部分,以查看它们是否解析。

这个功能,在早期版本的Firefox中引入,对开发人员有点讨厌。 该功能意味着当在localhost上运行的服务器无法响应时,Firefox决定尝试localhost.comwww.localhost.com. 这通常解析为未找到的页面。

要禁用该功能

  1. 输入 about:config 到地址栏
  2. 输入browser.fixup.alternate.enabled在搜索栏
  3. 右键单击 browser.fixup.alternate.enabled 出现在以下过滤的列表中,并选择toggle以将值设置为false。

开启 mod_security

ModSecurity is a rule-based web application firewall that monitors web service traffic, to block attacks exploiting known vulnerabilities.

安装 www-apache/mod_security:

root #emerge --ask www-apache/mod_security

要开启apache2SECURITY模块,更改APACHE2_OPTS的值:

文件 /etc/conf.d/apache2开启安全模块
APACHE2_OPTS="... -D SECURITY"

通过编辑 /etc/apache2/modules.d/79_modsecurity.conf/etc/apache2/modules.d/80_modsecurity-crs.conf 文件来控制这个模块。文件 /usr/share/doc/mod_security-*/modsecurity.conf-recommended.bz2 包含推荐的配置 https://github.com/SpiderLabs/ModSecurity/wiki/Reference-Manual#A_Recommended_Base_Configuration。将基本配置复制到 /etc/apache2/modules.d/79_modsecurity.conf 并根据需要调整设置。将文件 /usr/share/doc/modsecurity-crs-*/crs-setup.conf.example.bz2 解压到合适的位置,例如/etc/conf.d/crs-setup.conf,调整它,并将解压后的文件包含在 /etc/apache2/modules.d/80_modsecurity-crs.conf 中。最后,重启 Apache。在网站的 Apache 日志文件中查找错误并采取相应措施。

开启 PHP 支持

安装 PHP 附带 apache2 USE 标记,然后开启PHP模块:

文件 /etc/conf.d/apache2开启PHP模块
APACHE2_OPTS="... -D PHP"

在测试PHP模块是否工作前,检查文件 /etc/apache2/modules.d/70_mod_php.conf 是否存在,是否包含以下默认值。

文件 /etc/apache2/modules.d/70_mod_php.conf验证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>

如果不存在请手动创建一个。

要验证PHP模块是否启动,创建个测试页面:

文件 /var/www/localhost/htdocs/index.phpPHP 测试页
<html>
 <body>
  <?php phpinfo(); ?>
 </body>
</html>

现在,把他重命名为 /var/www/localhost/htdocs/index.html,然后打开测试页面:http://localhost/

应该可以看到一个描述PHP配置的表格。

修改 PHP 版本

要更改Apache处理的PHP版本,首先列出 apache2 服务器应用程序编程接口(SAPI)的可用版本:

root #选择 PHP 用于apache2
 [1]   php5.3
 [2]   php5.4 *
 [3]   php5.5

改变选择:

root #eselect php set apache2 N

正如前面上显示,替换N在上面的例子中输出请求的值:eselect php list apache2

虚拟主机

对于每个虚拟主机提供一个DocumentRoot,它是由Apache守护进程控制的目录。 在(VirtualHost.conf)目录中添加使用此DocumentRoot 和虚拟主机服务器的虚拟主机配置文件 /etc/apache2/vhosts.d。 不要忘了在/etc/hosts添加一个该域名的条目 。

要在虚拟主机文件上分配apache user/group 所有权,请使用chown ,如以下示例所示:

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

下面是两个示例虚拟主机的例子,一个用于domainname1.com,一个用于domainname2.com。 注意使用不同的DocumentRootServerName指令,即时主机本身(*:80)保持不变:

代码 几个虚拟主机的例子
<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>

建议也提供基于IP的虚拟主机。 这允许管理员尝试为通过其IP地址访问网站的用户发送消息:

代码 IP-based虚拟主机
<VirtualHost *:80>
    ServerAdmin email@site.com
    DocumentRoot /var/www/html
    ServerName xxx.xxx.xxx.xxx
</VirtualHost>

加入虚拟主机后,服务器需要(正常)重新启动以使新站点变为活动状态。

通过fcgid 开启 PHP

安装 www-apache/mod_fcgiddev-lang/php。 PHP 这个包需要有 cgi 这个 USE 标记:

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

编辑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>

创建所需要的目录:

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

软链接到PHP wrapper:

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

开启FCGID模块:

文件 /etc/conf.d/apache2开启fcgid 模块
APACHE2_OPTS="... -D FCGID"

最后重启并检查phpinfo()Server API 应该被设置为 CGI/FastCGI

在Apache 2.4上通过 mod_proxy_fcgi开启PHP-FPM

必须满足以下条件才能通过mod_proxy_fcgi启用PHP-FPM:

  • >= PHP 5.3
  • >= Apache 2.4

此外,Apache 2.4中的功能的可用性有一些限制:

以下配置将仅适用于Apache 2.4.10及更高版本。 它依赖于FilesMatch指令,并放在主服务器配置或VirtualHosts中。 UNIX socket的位置由 php-fpm.conf配置文件中的listen指令确定,允许为每个站点或函数指定单独的池。

在下面的例子中 FilesMatch 被放在Apache的PHP模块配置文件中:

文件 /etc/apache2/modules.d/70_mod_php.conf使用PHP-FPM ( Apache 2.4.10 或更新 推荐使用)
<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>

或者,您可以使用ProxyPassMatch - 这是唯一的选项,如果Apache版本在2.4.0和2.4.8之间。

文件 /etc/apache2/modules.d/70_mod_php.conf使用PHP-FPM (建议在 Apache 2.4.8 或更老的版本上使用)
<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>

默认情况下, listen指令未设置为socket。 首先创建socket文件的目录:

root #mkdir /var/run/php-fpm

接下来,像下面这样更新php-fpm.conf:

文件 php-fpm.conf更新监听指令
; 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

同时开启PHPPROXY 模块:

文件 /etc/conf.d/apache2开启 PHP 和 proxy 模块
APACHE2_OPTS="... -D PHP -D PROXY"

Web frameworks and Apache

Some of the web frameworks that can work with Apache are covered on the wiki:

HTTPS with TLS certificates from Let’s Encrypt

It is important that any public-facing web server provide "secure" HTTPS access. Often, sites providing HTTPS will be configured to redirect HTTP requests to the HTTPS equivalent URL.

Let’s Encrypt is a not-for-profit certificate authority that issues free TLS certificates. certbot is a utility available in the Gentoo repository for easily requesting and installing TLS certificates, and automatically setting up HTTPS access for Apache.

See the Let's Encrypt article for information about using certbot. The EFF also have specific instructions on using certbot on Gentoo to configure Apache.

用法

服务

OpenRC

开启Apache服务

root #/etc/init.d/apache2 start

将Apache添加至default runlevel:

root #rc-update add apache2 default

重启Apache服务

root #/etc/init.d/apache2 restart

重新读取Apache配置文件:

root #/etc/init.d/apache2 reload

systemd

开启Apache服务

root #systemctl start apache2

将Apache添加至default runlevel:

root #systemctl enable apache2

重启Apache服务

root #systemctl restart apache2

故障排除

资源

Apache很难配置的很好。下面是一些可能有用的资源,如果你遇到错误可以看看。

测试

验证Apache上一个IP端口是否开启并监听:

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        

测试Apache服务器在localhost上是否正常工作:

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

可以使用Ctrl+c 或者 Enter来中断测试。

apr_sockaddr_info_get() failed for <System_Hostname>

错误:

apache2: apr_sockaddr_info_get() failed for System_Hostname

解析:

发生这种情况时,请将主机名添加到 /etc/hosts文件中:

文件 /etc/hosts添加一个 Hostname 到 Apache
127.0.0.1 localhost System_Hostname

另请参阅

外部资源