1. 首页 > IT综合教程 > 正文

256. Apache HTTP Server培训

一、Apache HTTP Server概述

Apache HTTP Server是世界上使用最广泛的Web服务器软件之一,功能强大、模块丰富、稳定性高,支持多种操作系统。

风哥风哥提示:

1.1 Apache核心特性

  • 模块化设计:丰富的模块扩展功能
  • 虚拟主机:支持基于IP、端口、域名的虚拟主机
  • URL重写:强大的mod_rewrite模块
  • 代理服务:正向代理和反向代理支持

二、Apache安装部署

2.1 YUM安装

# 安装Apache
yum install -y httpd httpd-devel

# 安装常用模块
yum install -y mod_ssl mod_proxy mod_proxy_http mod_rewrite

# 启动服务
systemctl start httpd
systemctl enable httpd

# 查看版本
httpd -v

# 查看编译参数
httpd -V
# 输出示例
Server version: Apache/2.4.57 (CentOS Stream)
Server built: Jan 15 2024 00:00:00
Server’s Module Magic Number: 20120211:107
Server loaded: core mod_so http_core
Compiled using: APR 1.7.0, APR-UTIL 1.6.1

2.2 源码编译安装

# 安装依赖
yum install -y gcc pcre-devel zlib-devel openssl-devel expat-devel

# 下载源码
wget https://archive.apache.org/dist/httpd/httpd-2.4.58.tar.gz
wget https://archive.apache.org/dist/apr/apr-1.7.3.tar.gz
wget https://archive.apache.org/dist/apr/apr-util-1.6.3.tar.gz

# 解压
tar -xzf httpd-2.4.58.tar.gz
tar -xzf apr-1.7.3.tar.gz
tar -xzf apr-util-1.6.3.tar.gz

# 移动APR到httpd源码目录
mv apr-1.7.3 httpd-2.4.58/srclib/apr
mv apr-util-1.6.3 httpd-2.4.58/srclib/apr-util

# 配置编译
cd httpd-2.4.58
./configure \
    --prefix=/usr/local/apache2 \
    --with-included-apr \
    --enable-so \
    --enable-ssl \
    --enable-proxy \
    --enable-rewrite \
    --enable-mods-shared=all

# 编译安装
make && make install

# 创建systemd服务
cat > /etc/systemd/system/httpd.service << 'EOF'
[Unit]
Description=The Apache HTTP Server
After=network.target

[Service]
Type=forking
ExecStart=/usr/local/apache2/bin/apachectl start
ExecStop=/usr/local/apache2/bin/apachectl stop
ExecReload=/usr/local/apache2/bin/apachectl graceful
PIDFile=/usr/local/apache2/logs/httpd.pid

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl start httpd

三、主配置文件

3.1 基本配置

# /etc/httpd/conf/httpd.conf

# 服务器根目录
ServerRoot "/etc/httpd"

# 监听端口
Listen 80

# 加载模块
LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_core_module modules/mod_authn_core.so
LoadModule authz_host_module modules/mod_authz_host.so

# 用户和组
User apache
Group apache

# 服务器管理员
ServerAdmin root@fgedudb

# 服务器名称
ServerName www.fgedu.net.cn:80

# 文档根目录
DocumentRoot "/var/www/html"

# 目录权限
<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

# 索引文件
DirectoryIndex index.html index.htm index.php

# 日志配置
ErrorLog "logs/error_log"
LogLevel warn
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
CustomLog "logs/access_log" combined

# 包含其他配置
Include conf.modules.d/*.conf
IncludeOptional conf.d/*.conf

3.2 MPM配置

# Prefork MPM(默认)
<IfModule mpm_prefork_module>
    StartServers             5
    MinSpareServers          5
    MaxSpareServers         10
    MaxRequestWorkers      150
    MaxConnectionsPerChild   0
</IfModule>

# Worker MPM
<IfModule mpm_worker_module>
    StartServers             2
    MinSpareThreads         25
    MaxSpareThreads         75
    ThreadLimit             64
    ThreadsPerChild         25
    MaxRequestWorkers      150
    MaxConnectionsPerChild   0
</IfModule>

# Event MPM(推荐)
<IfModule mpm_event_module>
    StartServers             2
    MinSpareThreads         25
    MaxSpareThreads         75
    ThreadLimit             64
    ThreadsPerChild         25
    MaxRequestWorkers      150
    MaxConnectionsPerChild   0
</IfModule>

四、虚拟主机配置

4.1 基于域名的虚拟主机

# /etc/httpd/conf.d/vhosts.conf

NameVirtualHost *:80

# 虚拟主机1
<VirtualHost *:80>
    ServerAdmin webmaster@fgedu.net.cn
    ServerName www.fgedu.net.cn
    ServerAlias fgedu.net.cn
    DocumentRoot /var/www/example
    
    ErrorLog logs/example-error.log
    CustomLog logs/example-access.log combined
    
    <Directory "/var/www/example">
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

# 虚拟主机2
<VirtualHost *:80>
    ServerAdmin webmaster@test.com
    ServerName www.test.com
    DocumentRoot /var/www/test
    
    ErrorLog logs/test-error.log
    CustomLog logs/test-access.log combined
</VirtualHost>

4.2 基于端口的虚拟主机

# 监听多个端口
Listen 80
Listen 8080
Listen 8443

# 端口80虚拟主机
<VirtualHost *:80>
    ServerName www.fgedu.net.cn
    DocumentRoot /var/www/main
</VirtualHost>

# 端口8080虚拟主机
<VirtualHost *:8080>
    ServerName www.fgedu.net.cn
    DocumentRoot /var/www/admin
</VirtualHost>

五、SSL/TLS配置

5.1 HTTPS虚拟主机

# /etc/httpd/conf.d/ssl.conf

LoadModule ssl_module modules/mod_ssl.so

Listen 443 https

<VirtualHost *:443>
    ServerName www.fgedu.net.cn
    DocumentRoot /var/www/example
    
    SSLEngine on
    SSLCertificateFile /etc/pki/tls/certs/fgedu.net.cn.crt
    SSLCertificateKeyFile /etc/pki/tls/private/fgedu.net.cn.key
    SSLCertificateChainFile /etc/pki/tls/certs/ca-bundle.crt
    
    SSLProtocol all -SSLv2 -SSLv3
    SSLCipherSuite HIGH:!aNULL:!MD5:!3DES
    SSLHonorCipherOrder on
    
    <Directory "/var/www/example">
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>

# HTTP重定向HTTPS
<VirtualHost *:80>
    ServerName www.fgedu.net.cn
    Redirect permanent / https://www.fgedu.net.cn/
</VirtualHost>

六、反向代理配置

6.1 基本反向代理

# 加载代理模块
LoadModule proxy_module modules/mod_proxy.so
LoadModule proxy_http_module modules/mod_proxy_http.so

# 反向代理配置
<VirtualHost *:80>
    ServerName api.fgedu.net.cn
    
    ProxyPreserveHost On
    ProxyPass / http://fgedudb:8080/
    ProxyPassReverse / http://fgedudb:8080/
    
    # 超时设置
    ProxyTimeout 300
</VirtualHost>

# 负载均衡
<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 api.fgedu.net.cn
    ProxyPass / balancer://mycluster/
    ProxyPassReverse / balancer://mycluster/
</VirtualHost>

6.2 AJP代理

# 加载AJP模块
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so

# AJP代理配置
<VirtualHost *:80>
    ServerName tomcat.fgedu.net.cn
    
    ProxyPass / ajp://fgedudb:8009/
    ProxyPassReverse / ajp://fgedudb:8009/
</VirtualHost>

七、URL重写

7.1 mod_rewrite配置

# 加载重写模块
LoadModule rewrite_module modules/mod_rewrite.so

# 启用重写
<Directory "/var/www/html">
    AllowOverride All
</Directory>

# .htaccess重写规则
RewriteEngine On

# 简单重定向
RewriteRule ^old-page\.html$ /new-page.html [R=301,L]

# 伪静态
RewriteRule ^article/([0-9]+)\.html$ article.php?id=$1 [L]

# 域名重定向
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ http://www.fgedu.net.cn/$1 [R=301,L]

# HTTP转HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# 防盗链
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?example\.com/ [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F,NC]

八、访问控制

8.1 目录访问控制

# 基于IP的访问控制
<Directory "/var/www/admin">
    Require ip 192.168.1.0/24
    Require ip 10.0.0.0/8
</Directory>

# 基于用户的认证
<Directory "/var/www/private">
    AuthType Basic
    AuthName "Restricted Area"
    AuthUserFile /etc/httpd/.htpasswd
    Require valid-user
</Directory>

# 创建密码文件
htpasswd -c /etc/httpd/.htpasswd admin
htpasswd /etc/httpd/.htpasswd user1

# 禁止访问敏感文件
<FilesMatch "^\.ht">
    Require all denied
</FilesMatch>

<FilesMatch "\.(log|sql|bak)$">
    Require all denied
</FilesMatch>

九、性能优化

9.1 性能调优

# 启用压缩
LoadModule deflate_module modules/mod_deflate.so
<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/html text/plain text/xml
    AddOutputFilterByType DEFLATE text/css application/javascript
    AddOutputFilterByType DEFLATE application/json application/xml
</IfModule>

# 启用缓存
LoadModule cache_module modules/mod_cache.so
LoadModule cache_disk_module modules/mod_cache_disk.so
<IfModule mod_cache.c>
    CacheQuickHandler on
    CacheLock on
    CacheLockPath /tmp/cachelock
    CacheLockMaxAge 5
    CacheIgnoreHeaders Set-Cookie
</IfModule>

# 启用过期头
LoadModule expires_module modules/mod_expires.so
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/jpg "access plus 30 days"
    ExpiresByType image/jpeg "access plus 30 days"
    ExpiresByType image/gif "access plus 30 days"
    ExpiresByType image/png "access plus 30 days"
    ExpiresByType text/css "access plus 7 days"
    ExpiresByType application/javascript "access plus 7 days"
</IfModule>

# KeepAlive设置
KeepAlive On
KeepAliveTimeout 5
MaxKeepAliveRequests 100

十、运维命令

10.1 常用管理命令

# 测试配置
apachectl configtest
httpd -t

# 启动服务
systemctl start httpd

# 停止服务
systemctl stop httpd

# 重启服务
systemctl restart httpd

# 优雅重启(不中断连接)
systemctl reload httpd
apachectl graceful

# 查看状态
systemctl status httpd

# 查看已加载模块
httpd -M

# 查看进程
ps -ef | grep httpd

# 查看端口
netstat -tlnp | grep httpd

十一、最佳实践

配置项 建议值 说明
MPM event 高性能多路处理
KeepAlive On 启用持久连接
压缩 启用 减少传输大小
SSL TLSv1.2+ 安全传输
注意事项:

  • 定期检查日志文件大小
  • 及时更新安全补丁
  • 配置文件修改后需重载
  • 生产环境必须启用HTTPS

十二、总结

Apache HTTP Server是功能强大的Web服务器。通过本培训文档,您应该掌握了:

  • Apache的安装部署
  • 主配置文件和MPM配置
  • 虚拟主机配置
  • SSL/TLS安全配置
  • 反向代理和负载均衡
  • URL重写和访问控制
IT运维培训文档系列 | 第256篇 | Apache HTTP Server培训

本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html

联系我们

在线咨询:点击这里给我发消息

微信号:itpux-com

工作日:9:30-18:30,节假日休息