一、Apache 概述与安装

1. 介绍

Apache HTTP Server(简称 Apache)是 Apache 软件基金会的一个开源的网页服务器,是世界使用排名第一的 Web 服务器软件。它可以运行在几乎所有广泛使用的计算机平台上,由于其跨平台和安全性被广泛使用,是最流行的 Web 服务器端软件之一。

Apache 的服务名称是 httpd。

2. 安装

1
yum -y install httpd

3. 快速入门

3.1 Apache 基本管理

1
2
3
4
5
6
7
8
# Apache 状态管理
systemctl start|stop|restart|reload|status httpd.service

# 设置 Apache 开机启动
systemctl enable httpd.service

# 设置 Apache 开机不启动
systemctl disable httpd.service

3.2 站点根目录

Apache 默认站点根目录:/var/www/html

3.3 Apache 服务目录介绍

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/etc/httpd/
├── conf # 主配置文件目录
│ ├── httpd.conf
│ └── magic
├── conf.d # 模块化配置文件目录(辅助配置文件目录)
│ ├── autoindex.conf
│ ├── README
│ ├── userdir.conf
│ └── welcome.conf
├── conf.modules.d # 模块配置文件目录
│ ├── 00-base.conf
│ ├── 00-dav.conf
│ ├── 00-lua.conf
│ ├── 00-mpm.conf
│ ├── 00-proxy.conf
│ ├── 00-systemd.conf
│ └── 01-cgi.conf
├── logs -> /var/log/httpd # 日志目录
├── modules -> /usr/lib64/httpd/modules # 模块目录
└── run -> /run/httpd # 运行时目录

3.4 Apache 用户

Apache 在安装后会创建一个叫做 apache 的用户,Apache 的子进程就是用这个用户运行的。

1
2
tail -1 /etc/passwd
# apache:x:48:48:Apache:/usr/share/httpd:/sbin/nologin

4. Apache 基本概念

4.1 Apache 进程

  • Apache 默认监听 TCP 协议的 80 端口
  • Apache 默认会启动一个主进程(控制进程)和多个子进程

查看 Apache 相关进程:

1
ps aux | grep httpd

其中 root 运行的是主进程,apache 身份运行的是子进程,主进程的 ID 保存在 /etc/httpd/run/httpd.pid 文件内。真正用来处理 Web 请求的是子进程,主进程用来管理子进程。

4.2 Apache 模块

  • Apache 是一个模块化设计的服务,核心只包含主要功能,扩展功能通过模块实现(可扩展性强,各功能依赖性低)
  • 不同模块可以被静态的编译进程序,也可以动态加载
  • 模块的动态加载通过 DSO(Dynamic Shared Object)实现

查看模块:

1
httpd -M

二、Apache 配置详解及实践

1. 配置文件说明

1.1 主配置文件位置

/etc/httpd/conf/httpd.conf

1.2 配置文件格式

1
2
# directive(指令)    value(值)
ServerRoot "/etc/httpd"

2. 配置项详解

2.1 ServerRoot

服务所在目录的路径,不需要做修改。

1
ServerRoot "/etc/httpd"

2.2 Listen

监听端口。

1
Listen 80

配置语法:Listen [IP-address:]portnumber [protocol]

检查配置的语法是否正确:

1
httpd -t

实践:

1
2
3
4
5
6
7
8
9
# 1. 修改端口号
Listen 8080

# 2. Listen 指令可重复出现多次
Listen 8080
Listen 80

# 注意:修改后必须重启服务才可生效
systemctl restart httpd.service

2.3 Include

导入配置文件。

1
Include conf.modules.d/*.conf

2.4 IncludeOptional

和 Include 功能相同,都是导入配置文件。区别是 IncludeOptional 导入的路径有问题时会被忽略,不会报错。

1
IncludeOptional conf.d/*.conf

2.5 User 和 Group

httpd 服务子进程启动时的账号和组,不需要修改。

1
2
User apache
Group apache

2.6 ServerAdmin

服务运行时的管理员邮箱地址。

1
ServerAdmin root@localhost

2.7 DocumentRoot

站点根目录。

1
DocumentRoot "/var/www/html"

实践:

1
2
3
4
5
# 修改站点根目录
DocumentRoot "/www"

# 同时需要修改 Directory 标签
<Directory "/www">

2.8 Directory

确定访问目录位置,标签配置。标签内是设置针对该目录的访问权限。

1
2
3
4
5
<Directory "/var/www/html">
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>

Options:访问时展示形式

选项 说明
Indexes 当前目录下没有默认页面,就显示目录结构
FollowSymLinks 默认设置,允许访问符号链接
None 关闭所有选项

AllowOverride.htaccess 文件中允许的指令类型

选项 说明
All 全部指令
None 默认值,不允许
directive-type 具体指令类型

Require:访问权限设置

选项 说明
Require all granted 无条件允许访问
Require all denied 无条件拒绝访问
Require method http-method 仅允许给定的 HTTP 方法访问
Require ip 10 172.20 192.168.2 指定 IP 地址范围的客户端可以访问

实践:

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
# 1. 去掉 Indexes 查看效果
<Directory "/var/www/html">
Options FollowSymLinks
AllowOverride None
Require all granted
</Directory>

# 2. 去掉 FollowSymLinks
<Directory "/var/www/html">
Options None
AllowOverride None
Require all granted
</Directory>

# 3. 使用 Require
<Directory "/var/www/html">
Options None
AllowOverride None
Require all denied # 无条件拒绝访问
</Directory>

<Directory "/var/www/html">
Options None
AllowOverride None
Require method POST # 仅允许 POST 请求
</Directory>

2.9 IfModule

以特定模块存在与否为条件的处理指令。

1
2
3
<IfModule dir_module>
DirectoryIndex index.html # 站点默认展示页
</IfModule>

语法:DirectoryIndex disabled | local-url [local-url] …

默认:DirectoryIndex index.html

2.10 Files

包含适用于匹配文件名的指令。

1
2
3
<Files ".ht*">
Require all denied # 以 .ht 开头的文件拒绝提供访问
</Files>

2.11 ErrorLog

错误日志记录位置。

1
ErrorLog "logs/error_log"

2.12 LogLevel

错误日志记录级别。

1
LogLevel warn

错误级别选项:

级别 描述
emerg 紧急情况,系统无法使用
alert 必须立即采取行动
crit 关键条件
error 错误条件
warn 警告条件
notice 正常但重要的情况
info 基本信息
debug 调试级消息

2.13 IfModule log_config_module

访问日志配置模块。

1
2
3
4
5
6
7
8
9
10
11
12
<IfModule log_config_module>
# 访问日志3种格式:combined、common、combinedio
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common

<IfModule logio_module>
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
</IfModule>

# 确定访问日志位置和使用哪种日志格式
CustomLog "logs/access_log" combined
</IfModule>

日志格式说明:

标识 含义
%h 客户端 IP
%l Remote User,通常为一个减号
%u Remote user(非登录访问时,其为一个减号)
%t 服务器收到请求时的时间
%r 请求报文的首行,记录了此次请求的方法、URL 以及协议版本
%>s 响应状态码
%b 响应报文的大小(单位是字节),不包括响应报文的 HTTP 首部
%{Referer}i 请求报文中首部 Referer 的值,即从哪个页面跳转至当前页面
%{User-Agent}i 请求报文中首部 User-Agent 的值,即发出请求的应用程序

2.14 IfModule alias_module

文档映射。

1
2
3
4
5
6
7
8
9
10
<IfModule alias_module>
# Redirect: 外部重定向
# Redirect permanent /foo http://www.example.com/bar

# Alias: 将 URL 映射到文件系统位置
# Alias /webpath /full/filesystem/path

# ScriptAlias: 将 URL 映射到 CGI 脚本
ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"
</IfModule>
  • Redirect:外部重定向
  • Alias:将 URL 映射到文件系统位置
  • ScriptAlias:将 URL 映射到 CGI 脚本

2.15 AddDefaultCharset

响应内容的编码格式。

1
AddDefaultCharset UTF-8

三、虚拟主机配置

虚拟主机指的是在单一机器上运行多个网站。虚拟主机可以”基于 IP”(每个 IP 一个站点),或者”基于域名”(每个 IP 多个站点)。这些站点运行在同一物理服务器上。

虚拟主机配置语法:

1
2
3
4
5
<VirtualHost addr[:port] [addr[:port]] ...>
ServerName ...
DocumentRoot ...
...
</VirtualHost>

1. 基于域名

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
# 配置文件:/etc/httpd/conf.d/iplinux1.conf
<VirtualHost *:80>
DocumentRoot "/var/www/iplinux1/"
ServerName www.iplinux1.org
ErrorLog "iplinux1-error_log"
TransferLog "iplinux1-access_log"
<Directory "/var/www/iplinux1">
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
</VirtualHost>

# 配置文件:/etc/httpd/conf.d/iplinux2.conf
<VirtualHost *:80>
DocumentRoot "/var/www/iplinux2/"
ServerName www.iplinux2.org
ErrorLog "iplinux2-error_log"
TransferLog "iplinux2-access_log"
<Directory "/var/www/iplinux2">
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
</VirtualHost>

2. 基于 IP

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
# 配置文件:/etc/httpd/conf.d/iplinux1.conf
<VirtualHost 172.16.99.251>
DocumentRoot "/var/www/iplinux1/"
ServerName www.iplinux1.org
ErrorLog "iplinux1-error_log"
TransferLog "iplinux1-access_log"
<Directory "/var/www/iplinux1">
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
</VirtualHost>

# 配置文件:/etc/httpd/conf.d/iplinux2.conf
<VirtualHost 172.16.99.252>
DocumentRoot "/var/www/iplinux2/"
ServerName www.iplinux2.org
ErrorLog "iplinux2-error_log"
TransferLog "iplinux2-access_log"
<Directory "/var/www/iplinux2">
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
</VirtualHost>

四、Rewrite 重写

mod_rewrite 提供了基于正则表达式规则动态修改传入的请求 URL 的方法,可以定义任意的 URL 映射到内部的站点文件中。

1. Rewrite 需求

在使用 Apache 做 Web 服务器时,有时候出于 SEO 优化或者是 URL 路径的简洁,需要将输入的 URL 转换成更为友好的 URL,这时候就可以使用 Rewrite 重写功能。

使用 Rewrite 功能首先需要开启 mod_rewrite 模块,yum 安装的 Apache 默认已经开启。

2. Rewrite 使用详解

Rewrite 规则可以在 Directory 指令中进行配置。

Rewrite 学习的三个核心是 RewriteEngineRewriteCondRewriteRule

2.1 RewriteEngine

Rewrite 功能的总开关,用来开启 Rewrite 重写功能。

1
RewriteEngine on

2.2 RewriteCond

RewriteCond 定义规则条件,当请求满足 RewriteCond 配置的条件时,执行后面的 RewriteRule 语句。

1
2
3
RewriteEngine on
RewriteCond %{HTTP_USER_AGENT} ^Mozilla//5/.0.*
RewriteRule index index.html

上面的规则表示:如果匹配到 HTTP 请求中 HTTP_USER_AGENT 是 Mozilla//5/.0.* 开头的,访问 index 时会自动访问到 index.html。

RewriteCond 和 RewriteRule 是上下对应的关系,可以有 1 个或多个 RewriteCond 来匹配一个 RewriteRule。

RewriteCond 常见的 HTTP 请求匹配方式:

1
2
3
RewriteCond %{HTTP_REFERER} (www.mytest.com)
RewriteCond %{HTTP_USER_AGENT} ^Mozilla//5/.0.*
RewriteCond %{REQUEST_FILENAME} !-f

HTTP_REFERER:判断访问者的来源

1
2
3
RewriteCond %{HTTP_REFERER} (www.mytest.com)
RewriteRule (.*)$ mytest.html
# 如果访问的上一个页面是 www.mytest.com,无论当前访问的是哪个页面,都会跳转到 mytest.html

REQUEST_FILENAME:匹配当前访问的文件

1
2
3
4
5
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^news/sports/(\d+)\.html web/index\.php?c=news&a=sports&num=$1 [QSA,NC,L]

# 访问 news/sports/123.html,真实访问的是 web/index.php?c=news&a=sports&num=123
  • -f:是否是一个文件,判断是否不是一个文件:!-f
  • -d:是否是一个目录,判断是否不是一个目录:!-d
  • $1:表示第一个参数

2.3 RewriteRule

RewriteRule 是配合 RewriteCond 一起使用的,是 RewriteCond 成功匹配后的具体执行过程。

1
RewriteRule Pattern Substitution [flags]
  • Pattern:正则匹配
  • Substitution:匹配的替换内容
  • [flags]:参数限制

常用 flags:

Flag 说明
QSA qsappend(追加查询字符串),强制重写引擎在已有的替换字符串中追加一个查询字符串,而不是简单的替换
NC nocase(忽略大小写),使 Pattern 忽略大小写
R redirect(强制重定向),匹配 Pattern 后,Substitution 是一个 HTTP 地址 URL
L last(结尾规则),已经匹配到了就立即停止,不再匹配下面的 Rule,类似于编程语言中的 break

五、Apache 日志切割

1. 为什么要进行日志切割

随着网站访问量越来越大,Web 服务产生的日志文件也会越来越大,这个时候日志文件不仅占用了大量的服务器空间,而且日志分析也很麻烦。

2. 日志切割两种方式

2.1 rotatelogs

rotatelogs 是 Apache 自带的日志切割工具。

使用 rotatelogs 每天记录一个日志文件:

1
2
3
4
5
6
7
8
# 编辑 httpd 主配置文件 /etc/httpd/conf/httpd.conf
# 注释下面两行
# ErrorLog "logs/error_log"
# CustomLog "logs/access_log" combined

# 添加下面两行
ErrorLog "|/usr/sbin/rotatelogs -l logs/error_%Y%m%d.log 86400"
CustomLog "|/usr/sbin/rotatelogs -l logs/access_%Y%m%d.log 86400" combined

说明:86400 为轮转的时间,单位为秒(即一天)。

2.2 cronolog

Cronolog 是一款日志轮循(rotation)工具,可以用它来把 Apache、Tomcat 等 Web 服务器上输出的日志切分成按日或月保存的文件。

安装:

1
2
3
tar zxf cronolog-1.6.2.tar.gz
cd cronolog-1.6.2/
./configure && make && make install

使用 cronolog 每天记录一个日志文件:

1
2
ErrorLog "|/usr/local/sbin/cronolog logs/error-%Y%m%d.log"
CustomLog "|/usr/local/sbin/cronolog logs/access-%Y%m%d.log" combined

按小时轮询生成日志:

1
CustomLog "|/usr/local/sbin/cronolog logs/access_%Y%m%d%H.log" combined

3. 总结

推荐使用 cronolog,因为 cronolog 稳定性高且配置简单。

六、Apache 防盗链

防盗链就是防止别人网站代码里调用我们服务器的图片、文件、视频等资源。如果别人盗用我们的资源,会增加服务器的带宽压力。

通过防盗链的方式,可以设置限制第三方的站点通过引用的方式获取服务器上的图片,如果想要获取本站点的图片数据,只能通过本站点访问获取,这样也有效的减少了服务器的资源消耗。

1. Rewrite 实现防盗链

1
2
3
4
5
6
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://www.myitcast.com/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://www.myitcast.com$ [NC]
RewriteCond %{HTTP_REFERER} !^http://myitcast.com/.*$ [NC]
RewriteCond %{HTTP_REFERER} !^http://myitcast.com$ [NC]
RewriteRule .*\.(gif|jpg|swf)$ http://www.myitcast.com/link.png [R,NC]

说明:

  • 第 1 条:开启 Rewrite 重写
  • 第 2~5 条:开启受信任的站点,能够访问站点的图片资源
  • 第 6 条:访问站点的 gif|jpg|swf 等类型资源时,跳转到指定图片

2. SetEnvIfNoCase

通过判断浏览器头信息来阻止盗链请求。

1
2
3
4
5
6
7
SetEnvIfNoCase Referer "^$" local_ref
SetEnvIfNoCase Referer "www.benet.com/.*$" local_ref
SetEnvIfNoCase Referer "benet.com/.*$" local_ref
<Filesmatch "\.(mp3|mp4|zip|rar|jpg|gif)">
Require all denied
Require env local_ref
</Filesmatch>

说明:

  • SetEnvIfNoCase:当满足某个条件时,为变量赋值,即根据客户端请求属性设置环境变量
  • Referer:指明了请求当前资源原始资源的 URL

本站由 sswfive 使用 Stellar 1.42.1 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。

本站总访问量