---
Document:  世界技能大赛网络系统管理项目训练日志
Author:  黄道金
Role: 教练
Date: 2023.10.07-10.08
Subject: Linux
Task: Apache2
---

# Apache2

## 1. 基本概念

**WWW：** 万维网（亦作“Web”、“WWW”、“'W3'”，英文全称为“World Wide Web”），是一个由许多互相链接的超文本组成的系统，通过互联网访问。在这个系统中，每个有用的事物，称为一样“资源”；并且由一个全域“统一资源标识符”（URI）标识；这些资源通过超文本传输协议（Hypertext Transfer Protocol）传送给用户，而后者通过点击链接来获得资源。

**HTTP：** 超文本传输协议（英文：HyperText Transfer Protocol，缩写：HTTP）是互联网上应用最为广泛的一种网络协议。设计HTTP最初的目的是为了提供一种发布和接收HTML页面的方法。通过HTTP或者HTTPS协议请求的资源由统一资源标识符（Uniform Resource Identifiers，URI）来标识。

**Apache：** Apache HTTP Server（简称Apache）是Apache软件基金会的一个开放源码的网页服务器，可以在大多数计算机操作系统中运行，由于其多平台和安全性被广泛使用，是最流行的Web服务器端软件之一。

**httpd：** httpd是一些Linux系统中（如RHEL）的apache软件名称（apache早期由NCSA HTTPd修改而来）

### 其他的Web Server

![other webserver](images/apache/other_webserver.png)

引用自：[https://news.netcraft.com/archives/2019/04/22/april-2019-web-server-survey.html](https://news.netcraft.com/archives/2019/04/22/april-2019-web-server-survey.html)

## 2. 操作实例

### 2.1. 实例1 apache的安装配置

```shell
# 安装启动
root@apache-server:~# apt   install  -y   apache2  apache2-doc

root@apache-server:~# systemctl    status   apache2
● apache2.service - The Apache HTTP Server
   Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
   Active: active (running) since Wed 2019-05-08 09:41:24 CST; 52s ago
 Main PID: 1444 (apache2)
   CGroup: /system.slice/apache2.service
           ├─1444 /usr/sbin/apache2 -k start
           ├─1446 /usr/sbin/apache2 -k start
           └─1447 /usr/sbin/apache2 -k start

5月 08 09:41:24 apache-server systemd[1]: Starting The Apache HTTP Server...
5月 08 09:41:24 apache-server apachectl[1433]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using fe80::20c:29ff:fee3:affc. Set the 'ServerName' directive globally
5月 08 09:41:24 apache-server systemd[1]: Started The Apache HTTP Server.

root@apache-server:~# netstat   -ntupl  |grep  apache
tcp6       0      0 :::80                   :::*                    LISTEN      1444/apache2
```

#### 2.1.1. 测试

1. 在浏览器中测试

  ![apache test](images/apache/apache_test.png)

  > Linux下使用firefox

2. 在命令行中测试

  ```shell
    root@client:~# curl    http://192.168.38.101
  ```

  ```shell
   root@client:~# curl    http://192.168.38.101
  ```

3. 使用域名来访问
   
  因为网站通常都是通过域名来访问的，而不是IP，所以在实验过程中我们可以配置DNS服务器来配合httpd服务器的实现。
  而在生产环境通常域名解析的工作由域名提供商（或者DNS服务商）来提供解析的功能，一般情况下不需要自行搭建DNS，只需要把你所购买的域名解析到你的apache服务器所在的服务器IP地址（公网）即可。

  另外，在实验环境里面，如果只是测试apache, 其实不需要搭建DNS那么复杂，要实现域名到IP的解析访问，用客户端系统/etc/hosts文件即可。
  
#### 2.1.2. 补充： apache本地帮助文档

```bash
root@apache-server:/etc/apache2/conf-available# a2enconf apache2-doc
root@apache-server:~# systemctl    reload  apache2
root@apache-server:/etc/apache2/conf-enabled# cat  apache2-doc.conf
Alias /manual /usr/share/doc/apache2-doc/manual/

<Directory "/usr/share/doc/apache2-doc/manual/">
    Options Indexes FollowSymlinks
    AllowOverride None
    Require all granted
    AddDefaultCharset off
</Directory>
```

![apache manual](images/apache/apache_manual.png)

### 2.2. 实例2 修改web的默认主页  

```shell
root@apache-server:/var/www/html# cp   -a  index.html index.html.backup
root@apache-server:/var/www/html# vim  index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
        <head> <meta charset="UTF-8"></meta></head>
        <body>
                <h1>这是我的第一个网页</h1>
        </body>
</html>
# curl常用-i -I的参数查看httpd header信息

root@client:~# elinks   -dump   http://192.168.38.101
                               这是我的第一个网页
# 命令行下的浏览器还有w3m , lynx
```

### 2.3. 实例3 使用https连接访问

http协议是一个明文的传输，所以在一些敏感的数据或操作（比如登录，支付）时，需要进行传输加密。https协议就是通过ssl进行双向加密传输 .

实现https的三种方式：

1. 使用apache软件自带的key 和 crt
2. 使用自签名的crt
3. 使用权威的CA机构颁发的crt

#### 2.3.1. 使用apache软件自带的key 和 crt

```shell
root@apache-server:/etc/apache2# a2enmod  ssl
root@apache-server:/etc/apache2/mods-enabled# vim  ssl.conf
root@apache-server:/etc/apache2/sites-available# vim  default-ssl.conf
oot@apache-server:/etc/apache2/sites-available# a2ensite   default-ssl.conf
root@apache-server:/etc/apache2/sites-available# systemctl    restart   apache2

root@apache-server:/etc/apache2/sites-available# netstat   -ntupl |grep  apache
tcp6       0      0 :::443                  :::*                    LISTEN      2463/apache2
tcp6       0      0 :::80                   :::*                    LISTEN      2463/apache2

# 访问测试
```

> ??? 如何实现http自动跳转到https？

#### 2.3.2. 使用自签名的key和crt

```shell
root@apache-server:/etc/apache2/ssl# openssl   req  -new  -x509  -nodes -out  web.crt  -keyout  web.key
-----
Country Name (2 letter code) [AU]:CN
State or Province Name (full name) [Some-State]:Guangdong
Locality Name (eg, city) []:Guangzhou
Organization Name (eg, company) [Internet Widgits Pty Ltd]:gzittc
Organizational Unit Name (eg, section) []:best
Common Name (e.g. server FQDN or YOUR name) []:www.caoyi.com
Email Address []:123456@163.com

root@apache-server:/etc/apache2/ssl# ls
web.crt  web.key

root@apache-server:/etc/apache2/ssl# vim  ../sites-enabled/default-ssl.conf

SSLCertificateFile      /etc/apache2/ssl/web.crt
SSLCertificateKeyFile /etc/apache2/ssl/web.key

```

#### 2.3.3. 使用权威的CA机构颁发的crt(模拟CA)

```shell
# 第1步： web服务器生成加密的key
root@apache-server:/etc/apache2/ssl# openssl  genrsa  -out  server.key   2048

# web服务器生成签名请求csr
root@apache-server:/etc/apache2/ssl# openssl    req   -new  -key  server.key  -out server.csr
-----
Country Name (2 letter code) [AU]:CN
State or Province Name (full name) [Some-State]:Guangdong
Locality Name (eg, city) []:Guangzhou
Organization Name (eg, company) [Internet Widgits Pty Ltd]:Itnsa
Organizational Unit Name (eg, section) []:best
Common Name (e.g. server FQDN or YOUR name) []:www.motian.com
Email Address []:.

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:
```

```shell
第3步： 在CA服务器上建立用于签名的环境
root@ca:~# aptitude  install openssl
root@ca:~# /usr/lib/ssl/misc/CA.pl  -newca
...........................+++
writing new private key to './demoCA/private/cakey.pem'
Enter PEM pass phrase:  需要设置密码
Verifying - Enter PEM pass phrase: 重复密码
-----
略......
CA certificate is in ./demoCA/cacert.pem

```

```shell
第4步： 把webserver上的csr签名请求文件发送给CA到其签名目录
root@apache-server:/etc/apache2/ssl# scp   server.csr    192.168.38.103:/root/
root@ca:~# mv  server.csr   newreq.pem
```

```shell
#第5步： CA对csr文件进行签名
root@ca:~# /usr/lib/ssl/misc/CA.pl   -sign
root@ca:~# ls
demoCA  newcert.pem  newreq.pem
```

```bash
#第6步： 把新的签名好的证书回传给webserver
root@ca:~# scp   newcert.pem    192.168.38.101:/etc/apache2/ssl/server.crt
```

```bash
#第7步： 在site配置文件中引用即可
root@apache-server:/etc/apache2/ssl# ls  server.*
server.crt  server.csr  server.key

root@apache-server:/etc/apache2/ssl# vim   ../sites-enabled/default-ssl.conf
SSLCertificateFile      /etc/apache2/ssl/server.crt
SSLCertificateKeyFile /etc/apache2/ssl/server.key

```

### 2.4. 实例4 配置基于域名的虚拟主机

虚拟主机可以使一台httpd的服务器能够运行多个独立的网站。  
多个独立的网站可以基于不同域名，基于不同IP，基于不同的端口。
最常用的基于域名的虚拟主机。

```shell
root@apache-server:/etc/apache2/sites-available# grep   -Ev  '^(#|[[:blank:]]*#|$)'   000-default.conf  >>  001-motian.conf
<VirtualHost *:80>
        ServerName   www.motian.com
        DocumentRoot /srv/www/motian
        ErrorLog ${APACHE_LOG_DIR}/error-motian.log
        CustomLog ${APACHE_LOG_DIR}/access-moitan.log combined
</VirtualHost>

root@apache-server:/etc/apache2/sites-available# mkdir  -p  /srv/www/motian
root@apache-server:/etc/apache2/sites-available# echo "this  is  motian  web page." >>  /srv/www/motian/index.html

root@apache-server:/etc/apache2/sites-available# vim   002-caoyi.conf
<VirtualHost *:80>
    ServerName   www.caoyi.com
    DocumentRoot  /srv/www/caoyi
</VirtualHost>
<VirtualHost *:443>
    ServerName   www.caoyi.com
    DocumentRoot  /srv/www/caoyi
    SSLEngine on
    SSLCertificateFile     /etc/ssl/certs/ssl-cert-snakeoil.pem
    SSLCertificateKeyFile  /etc/ssl/private/ssl-cert-snakeoil.key
</VirtualHost>


root@apache-server:/etc/apache2/sites-available# mkdir   /srv/www/caoyi
root@apache-server:/etc/apache2/sites-available# echo "Caoyi  web page." >>  /srv/www/caoyi/index.html

root@apache-server:/etc/apache2/sites-available# a2ensite    001-motian.conf   002-caoyi.conf

root@apache-server:/etc/apache2/sites-available# vim   /etc/apache2/apache2.conf

<Directory />
        Options FollowSymLinks
        AllowOverride None
#       Require all denied
        Require all granted
</Directory>


```

### 2.5. 实例5 运行CGI

```shell
root@apache-server:/etc/apache2/conf-enabled# vim  serve-cgi-bin.conf
root@apache-server:/etc/apache2/conf-enabled# a2enmod  cgi   cgid
root@apache-server:/usr/lib/cgi-bin# vim  time.sh
#!/bin/bash

echo "Content-type: text/html"
echo ""

/bin/cat <<EOF3
<html>
<head><title>System time</title></head>
<body>
<h2 align="center">The time of this system is :
EOF3

/bin/date "+%F %X"

/bin/cat <<EOF4
</h2>
</body>
</html>
EOF4

root@apache-server:/usr/lib/cgi-bin# chmod   +x  time.sh
root@apache-server:/usr/lib/cgi-bin# systemctl   restart   apache2

```

> 如果用python实现显示系统时间呢？

### 2.6. 实例6 目录索引和页面用户认证

```shell
<Directory "/var/www">

Options Indexes FollowSymLinks    Indexes是对目录支持索引的选项，FollowSymLinks 支持软链接。

</Directory>
```

![apache dir index](images/apache/apache_dir_index.png)

```shell
# 在虚拟主机里面配置
        DocumentRoot /var/www/html
        <Directory /var/www/html>
                Options FollowSymLinks
                AuthName "Please enter your username and password?"
                AuthType  Basic
                AuthUserfile   /etc/apache2/.htpasswd
                Require valid-user
        </Directory>
```

```shell
root@apache-server:~# htpasswd   -cm   /etc/apache2/.htpasswd  user01
New password:
Re-type new password:
Adding password for user user01
root@apache-server:~# htpasswd   -m   /etc/apache2/.htpasswd  user02
New password:
Re-type new password:
Adding password for user user02
root@apache-server:~# cat   /etc/apache2/.htpasswd
user01:$apr1$OsKl9YuW$Lw.Eg/VOVe40VEWADv0Ms/
user02:$apr1$60Ij6N.D$yoLKWQsD5vzKLvVs4SVbm1
```

![apache auth](images/apache/apache_auth.png)

### 2.7. 实例7 用户空间

支持每个普通用户在自己的家目录创建网站

```shell
root@apache-server:/etc/apache2/mods-available# a2enmod   userdir
root@apache-server:/etc/apache2/mods-enabled# vim  userdir.conf
root@apache-server:/etc/apache2/mods-enabled# systemctl  reload  apache2

root@apache-server:/home# ls
demo  lisi  zhangsan

root@apache-server:/home# mkdir   -p   {zhangsan,lisi}/public_html

root@apache-server:/home# echo  "This   is  zhangsan  homepage"  >  zhangsan/public_html/index.html
root@apache-server:/home# echo  "This   is   lisi   homepage"  >  lisi/public_html/index.html

```

![apache user html](images/apache/apache_user_html.png)

> 思考：
实现用户空间的访问URL为以下格式：
<http://192.168.122.109/zhangsan/>   （提示：别名 或 url  rewrite 跳转）  
<http://zhangsan.www.motian.com/> （提示：二级域名，比较难）

### 2.8. 实例8 lamp架构

lamp/lnmp = linux +  apache/nginx  +  mysql/mariadb   + php (或者PREL/PYTHON/Ruby/go)

```shell

root@apache-server:/home# apt   install  mariadb-server  mariadb-client

root@apache-server:/home# apt   install  php php-gd php-mbstring php-mysql  php-mysqli   php-mysqlnd  php-pear php-opcache   php-zip   php-bz2

# mysql
root@apache-server:~# systemctl    status   mysqld
#或 
root@apache-server:~# systemctl    status  mariadb

root@apache-server:~# ps aux  |grep  mysql
mysql       634  0.1  3.6 710896 73716 ?        Ssl  09:09   0:02 /usr/sbin/mysqld

root@apache-server:~# ss -ntupl |grep  mariadb
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      634/mysqld  

root@apache-server:/etc/mysql# ls  -l
总用量 24
drwxr-xr-x 2 root root 4096 11月 29 10:30 conf.d
-rw------- 1 root root  277 5月  10 12:01 debian.cnf
-rwxr-xr-x 1 root root 1509 8月  11  2017 debian-start
-rw-r--r-- 1 root root  869 8月  11  2017 mariadb.cnf
drwxr-xr-x 2 root root 4096 5月  10 12:01 mariadb.conf.d
lrwxrwxrwx 1 root root   24 11月 29 10:30 my.cnf -> /etc/alternatives/my.cnf
-rw-r--r-- 1 root root  839 7月  10  2016 my.cnf.fallback

# apache2
# 在这里使用www.motian.com这个域名的虚拟主机。

# PHP

root@apache-server:/etc/apache2# ls  mods-enabled/  |grep   php
php7.0.conf
php7.0.load

root@apache-server:/srv/www/motian# rm   -rf  index.html
root@apache-server:/srv/www/motian# vim  index.php
<?php   phpinfo();   ?>
```

![apache phpinfo](images/apache/apache_phpinfo.png)

```shell

#  安装lamp的应用Wordpress

MariaDB [(none)]> grant  all  privileges  on  motianweb.*   to  'webadmin'@'localhost'   identified   by  'Skills39' ;
MariaDB [(none)]> quit
Bye


# 上传wordpress,解压缩
root@apache-server:/home/demo/wordpress# cp   -R   *   /srv/www/motian/

root@apache-server:/home/demo/wordpress# ps  aux  |grep  apache2
root        667  0.0  1.6 359716 34444 ?        Ss   09:09   0:00 /usr/sbin/apache2 -k start
www-data   1174  0.0  0.3 162968  6548 ?        S    09:14   0:00 /usr/sbin/apache2 -k start

root@apache-server:/home/demo/wordpress# chown   -R  www-data    /srv/www/motian

```

![apache wordpress setting](images/apache/apache_wordpress_setting.png)

![apache wordpress infomation](images/apache/apache_wordpress.infomation.png)

## 3. 本章总结

重点：

- https
- VirtualHost
- 网站权限管理
- Lamp

## 4. 技能实践

以下https均采用自签名证书：

1. 安装apache2, 创建网站首页内容为“This is my test page”， 支持https访问;
2. 配置apache2的运行用户和组为www;
3. 通过命令行工具从客户端访问apache2， 观察访问日志的增加；
4. 创建两个基于域名的虚拟主机，分别是www.up01.com  <www.up02.com> , 首页内容不同；
5. 虚拟主机www.up01.com 支持https协议访问；
6. 访问www.up02.com时需要用户和密码。

## 5. 扩展指引

- Dns 服务器 ： 192.168.100.101
- Apache服务器： 192.168.100.102
- CA服务器和Mysql 服务器：  192.168.100.103
- 客户端：192.168.100.104

1. 首先搭建DNS服务 ， 完成www.520linux.com、520linux.com的域名解析
2. 搭建LAMP架构，安装wordpress， 网站域名为www.520linux.com，并且中文网站；
3. <www.520linux.com的网站仅能够通过https访问（使用http访问自动跳转），使用CA机构签发证书，CA的根目录应该为/caroot；>
4. <http://www.520linux.com/downloads/> 目录（需要另外创建）支持文件列表索引，里面有4个文件（a.txt b.mp3  c.mp4  d.jpg）.
5. 当用户使用520linux.com访问的时候自动跳转到www.520linux.com;
6. 当用户使用其他IP访问时，应该被拒绝。
