Apache2安装配置合集

本文介绍Apache2的安装与配置及其相关的所有可能的内容。

安装

安装Apache主要软件,需要的模块。配置模块信息和加载的模块。

先安装软件

1
sudo apt install apache2

Ubuntu的主软件为Apache2,而centOS的主软件为httpd

1
2
apache2 -m
httpd -m

需要啥,就安装啥。

1
2
3
4
5
sudo apt install apache2-ssl-dev libapache2-mod-apreq2 libapache2-mod-bw libapache2-mod-encoding \
libapache2-mod-evasive libapache2-mod-fcgid libapache2-mod-form \
libapache2-mod-geoip libapache2-mod-md libapache2-mod-mime-xattr \
libapache2-mod-parser3 libapache2-mod-php libapache2-mod-qos \
libapache2-mod-watchcat libapache2-mod-xsendfile

使用命令查看加载了哪些插件:

1
apachectl -M

样例输出为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Loaded Modules:
core_module (static)
so_module (static)
watchdog_module (static)
http_module (static)
log_config_module (static)
logio_module (static)
version_module (static)
unixd_module (static)
access_compat_module (shared)
alias_module (shared)
auth_basic_module (shared)
authn_core_module (shared)
authn_file_module (shared)
authz_core_module (shared)
authz_host_module (shared)
authz_user_module (shared)
autoindex_module (shared)
deflate_module (shared)
dir_module (shared)
env_module (shared)
filter_module (shared)
mime_module (shared)
mpm_prefork_module (shared)
negotiation_module (shared)
php7_module (shared)
reqtimeout_module (shared)
setenvif_module (shared)
status_module (shared)

如果有的模块没有自动加载,就手动加载:

1
a2enmod modulename

同样的,手动卸载为:

1
a2dismod modulename

当然,也可以直接在配置文件中加载模块

1
LoadModule bw_module          /usr/lib64/httpd/modules/mod_bw.so

查看Apache2的运行状态

1
systemctl status apache2

如果没有问题就可以在浏览器打开 http://localhost 看看效果。

修改文件权限

修改文件权限

1
sudo vim /etc/apache2/apache2.conf

将directory的权限修改一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<Directory />
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>

<Directory /usr/share>
AllowOverride All
Require all granted
</Directory>

<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>

扩展模块

apache模块主要使用为配置式,我的几个模块配置为:

连接数限制

限制每个IP一次最多的连接数

1
2
3
4
5
6
<IfModule mod_limitipconn.c>
MaxConnPerIP 15
NoIPLimit image/*
NoIPLimit text/css
NoIPLimit application/x-javascript
</IfModule>

bw带宽限制模块

bandwidth模块用于限制访问带宽,比如说限制mkv格式的视频下载速度最大为200000b/s

1
2
3
4
5
6
BandWidthModule on
ForceBandWidthModule on
Bandwidth all 1048576 # 1024*1024b
MinBandwidth all -1
LargeFileLimit .avi 1 200000
LargeFileLimit .mkv 1 200000

mpm并发模块

控制并发访问

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<IfModule mpm_prefork_module>
StartServers 5
MinSpareServers 5
MaxSpareServers 10
MaxClients 150
MaxRequestWorkers 250
MaxConnectionsPerChild 1000
</IfModule>

<IfModule mpm_worker_module>
StartServers 3
ServerLimit 16
MaxClients 150
MinSpareThreads 75
MaxSpareThreads 250
ThreadLimit 100
ThreadsPerChild 25
MaxRequestsPerChild 100
MaxRequestWorkers 400
MaxConnectionsPerChild 5000
</IfModule>

<IfModule mpm_event_module>
StartServers 20
ServerLimit 100
MinSpareThreads 75
MaxSpareThreads 250
ThreadsPerChild 64
ThreadLimit 64
MaxRequestsPerChild 64
MaxRequestWorkers 400
MaxConnectionsPerChild 1000
</IfModule>

缓存设置

如果是使用PHP的动态网页,可以使用缓存来加快访问速度。采用的缓存插件有memcache/memcached/redis等等。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<IfModule mod_cache.c>
CacheDefaultExpire 86400
<IfModule mod_disk_cache.c>
CacheEnable disk /
CacheRoot /tmp/apacheCache
CacheDirLevels 5
CacheDirLength 4
CacheMaxFileSize 1048576
CacheMinFileSize 10
</IfModule>
</IfModule>

<IfModule mod_cache.c>
<IfModule mod_mem_cache.c>
CacheEnable mem /
MCacheMaxObjectCount 20000
MCacheMaxObjectSize 1048576
MCacheMaxStreamingBuffer 65536
MCacheMinObjectSize 10
MCacheRemovalAlgorithm GDSF
MCacheSize 131072
</IfModule>
</IfModule>

<IfModule mod_socache_memcache.c>
SSLSessionCache memcache:feater.top:80,feater.top:443
MemcacheConnTTL 10min
</IfModule>

<IfModule mod_socache_redis.c>
SSLSessionCache redis:feater.top:80,feater.top:443
RedisConnPoolTTL 10min
RedisTimeout 10min
</IfModule>

ssl

用于实现https访问

切换到/etc/apache2/sites-enabled文件夹下

软链接配置文件

1
ln -s ../sites-available/default-ssl.conf default-ssl.conf

在配置文件中添加

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#   Pass Phrase Dialog:
# Configure the pass phrase gathering process.
# The filtering dialog program (`builtin' is a internal
# terminal dialog) has to provide the pass phrase on stdout.
SSLPassPhraseDialog exec:/usr/libexec/httpd-ssl-pass-dialog

# Inter-Process Session Cache:
# Configure the SSL Session Cache: First the mechanism
# to use and second the expiring timeout (in seconds).
SSLSessionCache shmcb:/run/httpd/sslcache(512000)
SSLSessionCacheTimeout 300

#
# Use "SSLCryptoDevice" to enable any supported hardware
# accelerators. Use "openssl engine -v" to list supported
# engine names. NOTE: If you enable an accelerator and the
# server does not start, consult the error logs and ensure
# your accelerator is functioning properly.
#
SSLCryptoDevice builtin
#SSLCryptoDevice ubsec

SSLRandomSeed startup builtin
SSLRandomSeed startup file:/dev/urandom 512
SSLRandomSeed connect builtin
SSLRandomSeed connect file:/dev/urandom 512

#SSLStaplingCache shmcb:/tmp/stapling_cache(128000)

# 以下部分在<VirtualHost _default:443>里面

# List the protocol versions which clients are allowed to connect with.
# The OpenSSL system profile is used by default. See
# update-crypto-policies(8) for more details.
SSLProtocol all -SSLv2 -SSLv3
SSLProtocol TLSv1 TLSv1.1 TLSv1.2
SSLProxyProtocol all -SSLv3

# User agents such as web browsers are not configured for the user's
# own preference of either security or performance, therefore this
# must be the prerogative of the web server administrator who manages
# cpu load versus confidentiality, so enforce the server's cipher order.
SSLHonorCipherOrder on

# 修改加密套件如下
#SSLCipherSuite HIGH:!RC4:!MD5:!aNULL:!eNULL:!NULL:!DH:!EDH:!EXP:+MEDIUM
SSLCipherSuite ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4:!DH:!DHE
SSLProxyCipherSuite PROFILE=SYSTEM

SSLCertificateFile /root/.acme.sh/feater.top/feater.top.cer

SSLCertificateKeyFile /root/.acme.sh/feater.top/feater.top.key

SSLCertificateChainFile /root/.acme.sh/feater.top/fullchain.cer

SSLCACertificateFile /root/.acme.sh/feater.top/ca.cer

SSL有等级,一般设置完成之后是A级,如果需要A+级,可以在配置文件中添加

1
2
3
4
5
6
7
#https
Protocols h2 http/1.1
#http
Protocols h2c http/1.1

# hsts
Header always set Strict-Transport-Security "max-age=15768000; includeSubdomains; preload"

将http重定向到https

配置到SSL证书之后,我们就可以使用https访问网站,为了防止有人在http下篡改网页内容(一般没有人会篡改小网站,但是网站有SSL功能显得专业),我们将http网址重定向到https下。

首先要保证网站文件目录的

1
AllowOverride None

修改为

1
AllowOverride All

/etc/apache2/sites-enabled/000-default.conf中添加

1
2
3
4
# redirect http to https
RewriteEngine on
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)?$ https://%{SERVER_NAME}$1 [L,R]

PHP

像WordPress、Typecho之类的博客框架会使用PHP,那么Apache2也要加载对应的PHP扩展模块。

先确定PHP主程序加载的扩展。

1
php -m

安装插件

1
2
3
4
5
6
7
8
sudo apt install php-bcmath php-bz2 php-cas php-curl php-date php-db php-ds \
php-embed php-enchant php-evenement php-gd php-geoip php-imagick \
php-gmp php-gnupg php-http php-http-request2 php-igbinary \
php-imagick php-imap php-intl php-json php-ldap php-log php-mail \
php-mail-mime php-markdown php-mbstring php-memcached php-mime-type \
php-mysql php-parser php-parsedown php-soap php-snmp php-sqlite3 \
php-ssh2 php-tidy php-timer php-twig php-uuid php-validate php-xml \
php-xmlrpc php-zip php-redis php-fpm

php插件基本上不需要配置,安装并加载就可以了。

如果有的插件没有自动加载,可以在PHP配置文件夹中的php.ini文件中添加

1
extension=redis

使用命令查看加载了哪些插件。

1
php -m

样例输出为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
[PHP Modules]
calendar
Core
ctype
date
exif
fileinfo
filter
ftp
gettext
hash
iconv
json
libxml
openssl
pcntl
pcre
PDO
Phar
posix
readline
Reflection
session
shmop
sockets
sodium
SPL
standard
sysvmsg
sysvsem
sysvshm
tokenizer
Zend OPcache
zlib

[Zend Modules]
Zend OPcache

安装配置完成之后要重启php-fpm服务

1
systemctl status php7.4-fpm

伪静态

apache还有一个文件.htaccess用于控制此网站的访问权限等等,位于网站源码的目录中。

默认HTML文件位置是/var/www/html,在网站文件目录下创建一个.htaccess文件,在里面添加以下代码用于伪静态。

1
2
3
4
5
6
7
8
9
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

当然要启动rewrite模块

1
2
a2enmod rewrite
systemctl restart apache2

vhost_alias_module多站点配置

之前买了一台阿里的云服务器2核8G80G硬盘,上面运行着本博客,后来因为阿里的骚操作太多,我把博客移至腾讯云。阿里的服务器就空闲了。

于是我在上面搭建了pdf.feater.top用于PDF电子书下载,但是只占用了不到1G内存,2核占用率加起来不到5%。于是我在上面又搭建了一个网站。

服务器系统是CentOS8.2+Apache2.4.37,只有一个vhost_alias_module模块。

/etc/httpd/httpd.conf中添加配置

1
2
3
4
5
6
7
8
9
10
11
12
13
<VirtualHost *:80>
ServerAdmin 1768478912@qq.com
DocumentRoot "/var/www/"
ServerName zabbix.feater.top
UseCanonicalName Off
VirtualDocumentRoot /var/www/%-3
<Directory "var/www">
Options FollowSymLinks
AllowOverride FileInfo AuthConfig Limit
Order allow,deny
Allow from all
</Directory>
</VirtualHost>

另一个站点域名为zabbix.feater.top

1
2
   3     2     1
zabbix.feater.top

从顶级域名开始向次级域名数,%-3zabbix

这样就实现了在同一台服务器,同一个IP下,同一个端口,运行两个网站。

日志输出

1
2
3
<FilesMatch ".(ico|gif|jpg|png|bmp|swf|css|js|svg)">
SetEnv IMAG 1
</FilesMatch>

上面用来过滤图片资源

1
CustomLog "|/usr/sbin/rotatelogs -l /var/log/httpd/access-%Y-%m-%d.log 86400" combined env=!IMAG

如果是图片资源就输入到日志中,否则就写入日志,按年月日分别保存


Apache2安装配置合集
https://blog.jackeylea.com/web/collections-of-apache2-installation-and-setup-and-modules/
作者
JackeyLea
发布于
2021年10月9日
许可协议