Apache HTTP Server is a free and open-source cross-platform web server software, released under the terms of Apache License 2.0.
Apache 概述
Apache HTTP Server(简称 Apache)是世界上最流行的 Web 服务器软件之一,由 Apache 软件基金会维护。Apache 的特点包括:
- 开源免费: 使用 Apache License 2.0
- 跨平台: 支持 Unix/Linux、Windows、macOS 等
- 模块化架构: 通过模块扩展功能
- 高度可配置: 灵活的配置系统
- 稳定可靠: 经过数十年的发展和验证
安装 Apache
Linux (Ubuntu/Debian)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| sudo apt update
sudo apt install apache2
sudo systemctl start apache2
sudo systemctl enable apache2
sudo systemctl status apache2
apache2 -v
|
Linux (CentOS/RHEL)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| sudo yum install httpd
sudo systemctl start httpd
sudo systemctl enable httpd
sudo systemctl status httpd
httpd -v
|
macOS
1 2 3 4 5 6 7 8
| brew install httpd
brew services start httpd
httpd -v
|
目录结构
Ubuntu/Debian
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| /etc/apache2/ ├── apache2.conf ├── ports.conf ├── sites-available/ │ └── 000-default.conf ├── sites-enabled/ ├── mods-available/ ├── mods-enabled/ ├── conf-available/ └── conf-enabled/
/var/www/html/ /var/log/apache2/ ├── access.log └── error.log
|
CentOS/RHEL
1 2 3 4 5 6 7 8 9 10 11
| /etc/httpd/ ├── conf/ │ └── httpd.conf ├── conf.d/ ├── conf.modules.d/ └── logs -> /var/log/httpd/
/var/www/html/ /var/log/httpd/ ├── access_log └── error_log
|
基本配置
主配置文件 (apache2.conf / httpd.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
| ServerRoot "/etc/apache2"
Listen 80
LoadModule rewrite_module modules/mod_rewrite.so LoadModule ssl_module modules/mod_ssl.so
ServerAdmin admin@example.com
ServerName www.example.com:80
DocumentRoot "/var/www/html"
<Directory "/var/www/html"> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory>
ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined
AddDefaultCharset UTF-8
|
虚拟主机配置
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
| <VirtualHost *:80> ServerName example.com ServerAlias www.example.com DocumentRoot /var/www/example.com/public_html
<Directory /var/www/example.com/public_html> Options -Indexes +FollowSymLinks AllowOverride All Require all granted </Directory>
ErrorLog ${APACHE_LOG_DIR}/example.com-error.log CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined </VirtualHost>
<VirtualHost 192.168.1.100:80> ServerName site1.example.com DocumentRoot /var/www/site1 </VirtualHost>
<VirtualHost *:8080> ServerName example.com DocumentRoot /var/www/site2 </VirtualHost>
|
SSL/HTTPS 配置
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
| Listen 443
<VirtualHost *:443> ServerName example.com DocumentRoot /var/www/example.com/public_html
SSLEngine on
SSLCertificateFile /etc/ssl/certs/example.com.crt SSLCertificateKeyFile /etc/ssl/private/example.com.key SSLCertificateChainFile /etc/ssl/certs/ca-bundle.crt
SSLProtocol all -SSLv2 -SSLv3 -TLSv1 -TLSv1.1 SSLCipherSuite HIGH:!aNULL:!MD5
<Directory /var/www/example.com/public_html> Options -Indexes +FollowSymLinks AllowOverride All Require all granted </Directory> </VirtualHost>
<VirtualHost *:80> ServerName example.com Redirect permanent / https://example.com/ </VirtualHost>
|
常用模块
mod_rewrite (URL 重写)
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
| sudo a2enmod rewrite # Ubuntu/Debian
LoadModule rewrite_module modules/mod_rewrite.so
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase /
RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME}\.php -f RewriteRule ^(.*)$ $1.php [L]
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.html [L] </IfModule>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| sudo a2enmod headers
<IfModule mod_headers.c> Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
Header set X-XSS-Protection "1; mode=block"
Header set X-Content-Type-Options "nosniff"
Header set X-Frame-Options "SAMEORIGIN"
Header set Content-Security-Policy "default-src 'self';"
Header set Access-Control-Allow-Origin "*" </IfModule>
|
mod_deflate (压缩)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| sudo a2enmod deflate
<IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css AddOutputFilterByType DEFLATE text/javascript application/javascript application/x-javascript AddOutputFilterByType DEFLATE application/xml application/xhtml+xml application/rss+xml AddOutputFilterByType DEFLATE application/json
BrowserMatch ^Mozilla/4 gzip-only-text/html BrowserMatch ^Mozilla/4\.0[678] no-gzip BrowserMatch \bMSIE !no-gzip !gzip-only-text/html </IfModule>
|
mod_expires (缓存控制)
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
| sudo a2enmod expires
<IfModule mod_expires.c> ExpiresActive On
ExpiresDefault "access plus 1 month"
ExpiresByType image/jpg "access plus 1 year" ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/gif "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType image/svg+xml "access plus 1 year" ExpiresByType image/x-icon "access plus 1 year"
ExpiresByType text/css "access plus 1 month" ExpiresByType text/javascript "access plus 1 month" ExpiresByType application/javascript "access plus 1 month"
ExpiresByType text/html "access plus 0 seconds" </IfModule>
|
.htaccess 文件
.htaccess 是 Apache 的分布式配置文件,允许在目录级别覆盖服务器配置。
启用 .htaccess
1 2 3 4
| <Directory /var/www/html> AllowOverride All </Directory>
|
常用 .htaccess 配置
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
| ErrorDocument 404 /404.html ErrorDocument 500 /500.html
Options -Indexes
DirectoryIndex index.html index.php home.html
AuthType Basic AuthName "Restricted Area" AuthUserFile /path/to/.htpasswd Require valid-user
Require all granted Require not ip 192.168.1.100
Require ip 192.168.1.0/24
php_value upload_max_filesize 20M php_value post_max_size 20M
RewriteEngine on RewriteCond %{HTTP_REFERER} !^$ RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC] RewriteRule \.(jpg|jpeg|png|gif)$ - [F]
|
性能优化
启用 MPM (多处理模块)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| apachectl -V | grep MPM
sudo a2dismod mpm_prefork sudo a2enmod mpm_event
<IfModule mpm_event_module> StartServers 2 MinSpareThreads 25 MaxSpareThreads 75 ThreadLimit 64 ThreadsPerChild 25 MaxRequestWorkers 150 MaxConnectionsPerChild 0 </IfModule>
|
启用 HTTP/2
1 2 3 4 5 6 7 8
| sudo a2enmod http2
<VirtualHost *:443> Protocols h2 http/1.1 </VirtualHost>
|
连接保持
1 2 3 4
| KeepAlive On MaxKeepAliveRequests 100 KeepAliveTimeout 5
|
日志管理
日志格式
1 2 3 4 5 6 7 8 9 10
| LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common
CustomLog ${APACHE_LOG_DIR}/access.log combined
SetEnvIf Request_URI "^/health-check$" dontlog CustomLog ${APACHE_LOG_DIR}/access.log combined env=!dontlog
|
日志轮转 (logrotate)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| /var/log/apache2/*.log { daily missingok rotate 14 compress delaycompress notifempty create 640 root adm sharedscripts postrotate /etc/init.d/apache2 reload > /dev/null endscript }
|
安全加固
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
| ServerTokens Prod ServerSignature Off
<Directory /var/www/html> Options -Indexes </Directory>
LimitRequestBody 10485760
Timeout 60
<Location /> <LimitExcept GET POST HEAD> Require all denied </LimitExcept> </Location>
<FilesMatch "^\."> Require all denied </FilesMatch>
<FilesMatch "(\.htaccess|\.htpasswd|\.git|\.env)"> Require all denied </FilesMatch>
|
常用命令
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
| sudo systemctl start apache2 sudo systemctl stop apache2 sudo systemctl restart apache2 sudo systemctl reload apache2
sudo apachectl configtest sudo apache2ctl -t
apachectl -M apache2ctl -M
sudo a2enmod rewrite sudo a2dismod rewrite
sudo a2ensite example.com.conf sudo a2dissite example.com.conf
apachectl -S
sudo tail -f /var/log/apache2/access.log sudo tail -f /var/log/apache2/error.log
netstat -an | grep :80 | wc -l
|
总结核心知识要点
Apache 架构
- MPM (多处理模块): prefork、worker、event 三种模式
- 模块化设计: 核心功能 + 可选模块(mod_rewrite、mod_ssl 等)
- 配置层级: 主配置 → 虚拟主机 → 目录 → .htaccess
核心配置示例
1. 完整虚拟主机配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <VirtualHost *:80> ServerName example.com ServerAlias www.example.com ServerAdmin admin@example.com DocumentRoot /var/www/example.com
<Directory /var/www/example.com> Options -Indexes +FollowSymLinks +MultiViews AllowOverride All Require all granted </Directory>
ErrorLog ${APACHE_LOG_DIR}/example.com-error.log CustomLog ${APACHE_LOG_DIR}/example.com-access.log combined
SetEnv APPLICATION_ENV production </VirtualHost>
|
2. HTTPS 虚拟主机 (Let’s Encrypt)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <VirtualHost *:443> ServerName example.com DocumentRoot /var/www/example.com
SSLEngine on SSLCertificateFile /etc/letsencrypt/live/example.com/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
SSLProtocol all -SSLv3 -TLSv1 -TLSv1.1 SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256 SSLHonorCipherOrder off SSLSessionTickets off
Header always set Strict-Transport-Security "max-age=63072000" </VirtualHost>
|
3. 反向代理配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
<VirtualHost *:80> ServerName api.example.com
ProxyPreserveHost On ProxyPass / http://localhost:3000/ ProxyPassReverse / http://localhost:3000/
RewriteEngine on RewriteCond %{HTTP:Upgrade} websocket [NC] RewriteRule /(.*) ws://localhost:3000/$1 [P,L] </VirtualHost>
|
4. 负载均衡配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
<Proxy "balancer://mycluster"> BalancerMember http://192.168.1.101:8080 BalancerMember http://192.168.1.102:8080 BalancerMember http://192.168.1.103:8080 ProxySet lbmethod=byrequests </Proxy>
<VirtualHost *:80> ServerName lb.example.com ProxyPass / balancer://mycluster/ ProxyPassReverse / balancer://mycluster/ </VirtualHost>
|
5. .htaccess 完整示例
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
| RewriteEngine On
RewriteCond %{HTTPS} off RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC] RewriteRule ^(.*)$ https://%1%{REQUEST_URI} [L,R=301]
RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?route=$1 [L,QSA]
<IfModule mod_headers.c> Header set X-Content-Type-Options "nosniff" Header set X-Frame-Options "SAMEORIGIN" Header set X-XSS-Protection "1; mode=block" </IfModule>
<IfModule mod_expires.c> ExpiresActive On ExpiresByType image/jpg "access plus 1 year" ExpiresByType image/jpeg "access plus 1 year" ExpiresByType image/png "access plus 1 year" ExpiresByType text/css "access plus 1 month" ExpiresByType application/javascript "access plus 1 month" </IfModule>
<IfModule mod_deflate.c> AddOutputFilterByType DEFLATE text/html text/css text/javascript application/javascript </IfModule>
|
重要指令对比
| 指令 |
作用 |
示例 |
DocumentRoot |
网站根目录 |
DocumentRoot /var/www/html |
ServerName |
主域名 |
ServerName example.com |
ServerAlias |
域名别名 |
ServerAlias www.example.com |
DirectoryIndex |
默认首页 |
DirectoryIndex index.html index.php |
AllowOverride |
.htaccess 权限 |
AllowOverride All |
Options |
目录选项 |
Options -Indexes +FollowSymLinks |
Require |
访问控制 |
Require all granted |
MPM 模式选择
| MPM |
特点 |
适用场景 |
| prefork |
多进程,每进程一个线程 |
PHP (非线程安全) |
| worker |
多进程 + 多线程 |
中等并发 |
| event |
异步事件驱动 |
高并发、HTTP/2 |
性能优化清单
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| sudo a2enmod deflate
sudo a2enmod expires sudo a2enmod headers
sudo a2enmod http2
sudo a2dismod mpm_prefork sudo a2enmod mpm_event
KeepAlive On
sudo a2dismod status sudo a2dismod autoindex
|
常见问题排查
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| sudo apachectl configtest
sudo tail -f /var/log/apache2/error.log
sudo netstat -tulpn | grep :80
ps aux | grep apache2
apachectl -S
ls -la /var/www/html/
curl -I http://example.com
|
最佳实践
- 分离配置文件: 每个站点独立配置文件
- 使用 SSL/TLS: 启用 HTTPS 和 HSTS
- 定期更新: 保持 Apache 和模块最新版本
- 日志管理: 配置日志轮转,避免磁盘占满
- 安全加固: 隐藏版本信息,禁用不必要的模块
- 性能监控: 使用 mod_status 监控服务器状态
- 备份配置: 修改前备份配置文件
核心概念
- 虚拟主机: 一台服务器托管多个网站
- 模块系统: 动态加载功能模块
- URL 重写: mod_rewrite 实现 URL 友好化
- 反向代理: 将请求转发到后端服务器
- 负载均衡: 分发请求到多个后端服务器
References