Web Service

2017-02-09  本文已影响37人  uangianlap

标签(空格分隔): Linux 运维 HTTP Web
实验主机:
❶ CentOS7.2 10.0.0.11
❷ CentOS6.8 10.0.0.61


HTTP协议: Hyper Text Mark Language,超文本传输协议.客户端/服务器端架构,服务器端监听在一个Socket(套接字)上,客户端也是通过一个Scoket向服务端发送请求信息.

HTTP版本

❶ HTTP/0.9: 原型版本
❷ HTTP/1.0: 增加了cache,MIME等功能
❸ HTTP/1.1: 扩展了cache,加入更多的首部 条件式请求

端口范围

IANA(The Internet Assigned Numbers Authority,互联网数字分配机构)是负责协调一些使Internet正常运作的机构。
常用端口分类:
❶ 0 ~ 1023: 众所周知,永久地分配给固定的应用程序使用,特权端口(仅root有权限使用)
❷ 1024 ~ 41951: 注册端口,但要示略宽松,分配给某程序注册使用.
❸ 40952+:客户端程序使用的随机端口,动态端口,或称为私有端口.

Linux系统中的本地端口范围查看可执行cat /proc/sys/net/ipv4/ip_local_port_range命令查看,默认是32768 ~ 61000,以下为这个文件的说明:
The /proc/sys/net/ipv4/ip_local_port_range defines the local port range that is used by TCP and UDP traffic to choose the local port. You will see in the parameters of this file two numbers: The first number is the first local port allowed for TCP and UDP traffic on the server, the second is the last local port number. For high-usage systems you may change its default parameters to 32768-61000 -first-last.

HTTP的事务与格式

HTTP的事务可分为request与response,即请求与响应.其格式分别如下
request:

<method> <URL><http version>
HEADERS:
<body>

response:

<http version> status code
<body>

URL: 定位互联网中的某一个资源

<scheme>://<user>:<passowrd>@<host>[:<port>]/<path>;<params>?<query>#<frag>

method:
GET HEAD POST PUT DELETE OPTIONS RACE ...
status code

1xx:信息类
2xx:成功类
3xx:重定向类
4xx:客户端错误类
5xx:服务端错误类

一次完整的Http请求响应过程:
(1) 建立或处理连接;接收或拒绝请求;
(2) 接收请求
(3) 处理请求:解析请求;
(4) 访问资源:
资源映射:DocumentRoot /var/www/html/
http://www.magedu.com/index.html --> /var/www/html/index.html
(5) 构建响应报文
(6) 发送响应报文
(7) 记录日志

HTTP协议的实现

HTTP常用首部

❶ 通用首部

❷ 请求首部(客户端)

❸ 响应首部

❹ 实体首部

❺ 扩展首部

httpd的安装与详细说明

yum -y install httpd # 安装httpd-2.4.6-45.el7.centos.x86_64
下面2个工具是作为依赖会被安装
httpd-tools
mailcap.noarch
httpd的程序环境

`/etc/httpd/conf/httpd.conf`   # 主配置文件
`/etc/httpd/conf.d`            # 辅助配置文件目录
`/etc/httpd/conf.modules.d`    # 加载模块的配置文件

httpd的Unit File说明

[Unit]
Description=The Apache HTTP Server              # 描述
After=network.target remote-fs.target nss-lookup.target
Documentation=man:httpd(8)
Documentation=man:apachectl(8)

[Service]
Type=notify
EnvironmentFile=/etc/sysconfig/httpd            # 给httpd设置额外的环境变量或传递额外的参数,如下面的$OPTIONS就在这里设置
ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND # 启动httpd需要执行的放在前台交给systemd处理
ExecReload=/usr/sbin/httpd $OPTIONS -k graceful # 重载时执行的命令
ExecStop=/bin/kill -WINCH ${MAINPID}
# We want systemd to give httpd some time to finish gracefully, but still want
# it to kill httpd after TimeoutStopSec if something went wrong during the
# graceful stop. Normally, Systemd sends SIGTERM signal right after the
# ExecStop, which would kill httpd. We are sending useless SIGCONT here to give
# httpd time to finish.
KillSignal=SIGCONT
PrivateTmp=true

[Install]
WantedBy=multi-user.target

httpd相关的命令与用法

/usr/sbin/httpd:
    httpd: 不接任何参数直接启动httpd
    -M: 列出httpd所有加载的静态的与共享的模块
    -t: 测试配置文件语法
    
/usr/sbin/apachectl: 管理httpd的一个shell脚本程序
    -k start:        开启httpd
    -k stop:         关闭httpd
    -k restart:      重启httpd
    -k  graceful:    优雅地重启httpd
    -k graceful-stop:优雅地关闭httpd
  

httpd配置指令说明

ServerRoot "/etc/httpd"  # httpd服务器配置的目录树的顶级目录,所有配置文件里的相对路径都是相对这个
Listen 80                # 默认httpd监听的IP与端口,可添加多个
KeepAlive On|Off         # 持久连接
KeepAliveTimeout NUM(ms) # 持久连接的超时时长
MaxKeepAliveRequests NUM # 一次持久连接允许的连接数目
LoadModule foo_module modules/mod_foo.so  # 加载指定模块文件
Include conf.modules.d/*.conf             # 包含其它的配置子文件,相对于ServerRoot目录
<IfModule [!]MODULE_NAME>:                # 指令块,里面放置一些指令,但是只能是在指定的模块存在时才有效
    "
    <IfModule dir_module>
        DirectoryIndex index.html   #定义站点主页面,可跟多个
    </IfModule>
    "
ErrorLog "logs/error_log":          # 指定错误日志文件存放的位置
LogLevel warn            :          # 日志级别
LogFormat:                          # 日志格式,可查看[日志格式][1]
    
CustomLog "logs/access_log" common: # 自定义日志文件
DocumentRoot "/var/www/html":       # 网站文档根目录
ServerName www.example.com:80:      # 服务器名
<Directory "/usr/local/httpd/htdocs"> # 设置指令的生效(作用)范围(本地文件系统)其中常用的包含指令有
    Options Indexes FollowSymLinks None All ...
    AllowOverride None  # Types of directives that are allowed in .htaccess files
    # Allow open access:
    Require all granted|denied
    #Require [not] ip IP|NETWORK
    #Require [not] host HOSTNAME
<Location /private2/>                # 同上但基于URL路径进行控制
Alias  /URL/  "/PATH/TO/SOME_DIR/"   # 路径别名,URL-文件系统
<VirtualHost IP:PORT>                # 定义虚拟主机 本机的IP与监听的端口
    ServerName
    DocumentRoot
</VirtualHost>
<Location /status>                   # 定义状态页面,通常放在status.conf
    SetHandler server-status
    Require all granted
</Location>
    
ExtendedStatus {On|Off}              # 是否输出扩展的状态信息
------------------------------------------------------------------------------
httpd-2.2:static                    # MPM机制说明
httpd-2.4:shared
    prefork:两级架构,由进程响应每个请求
        master process:1个, 
        child process:n个,
    worker:每线程响应一个请求;三级架构
        master process:1个
        child process:n个
            thread:m个
    event:每进程响应多个请求;
    
    prefork
        ServerLimit             
        StartServers
        MinspareServers
        MaxSpareServers
        MaxConnectionsPerchild
        MaxRequestWorkers 
        
    woker:
        ServerLimit
        StartServers
        MinSpareThreads
        MaxSpareThreads
        MaxRequestWorkers
        ThreadsPerChild 
        
    event:
        ThreadsPerChild
        MaxRequestWorkers
        AsyncRequestWorkerFactor
------------------------------------------------------------------------------      
AuthType basic                           # 用户认证
AuthName "Admin Area, Enter your name/password"
AuthUserFile "/etc/httpd/conf/.htpasswd" # htpasswd -c -m USERNAME [PWD]
Require valid-user
#AuthGroupFIle "/etc/httpd/conf/.htgroup"# 文件格式group_name: user1 user2 ..
#Require group 
------------------------------------------------------------------------------
使用mod_deflate模块压缩页面优化传输速度(需要装载deflate_module模块)
    适用场景:
        (1) 节约带宽,但会额外消耗CPU;同时,可能有些较老浏览器不支持;
        (2) 压缩适于压缩的资源,例如文件文件/etc/httpd/conf.d/deflate.conf;
    SetOutputFilter DEFLATE
    # mod_deflate configuration
    # Restrict compression to these MIME types
    AddOutputFilterByType DEFLATE text/plain
    AddOutputFilterByType DEFLATE text/html
    AddOutputFilterByType DEFLATE application/xhtml+xml
    AddOutputFilterByType DEFLATE text/xml
    AddOutputFilterByType DEFLATE application/xml
    AddOutputFilterByType DEFLATE application/x-javascript
    AddOutputFilterByType DEFLATE text/javascript
    AddOutputFilterByType DEFLATE text/css

    # Level of compression (Highest 9 - Lowest 1) 压缩级别
    DeflateCompressionLevel 9
    # Netscape 4.x has some problems.  浏览器匹配机制
    BrowserMatch ^Mozilla/4  gzip-only-text/html
    # Netscape 4.06-4.08 have some more problems 同上
    BrowserMatch  ^Mozilla/4\.0[678]  no-gzip
    # MSIE masquerades as Netscape, but it is fine
    BrowserMatch \bMSI[E]  !no-gzip !gzip-only-text/html

httpd调用ssl实现HTTPS安全传输

SSL会话的简化过程
    ㈠ 客户端发送可供选择的加密方式,并向服务器请求证书.
    ㈡ 服务器端发送证书以及选定的加密方式给客户端
    ㈢ 客户端取得证书并进行证书验证
        ① 验证证书的来源的合法性,用CA的公钥解密证书上数字签
        ② 验证证书的内容的合法性,完整性验证
        ③ 检查证书的有效期限
        ④ 检查证书是否被吊销 
        ⑤ 证书中拥有者的名字,与访问的目标主机要一对致
    ㈣ 客户端端生成临时会话密钥(对称密钥),并使用服务器端的公钥加密此数据发送给服务器,完成密钥交换
    ㈤ 服务用此密钥加密用户请求的资源,响应给客户端
注意:SSL会话是基于IP地址创建,所以单IP主机止,仅可以使用一个https虚拟主机.

配置实例

1. 确保httpd装载了ssl_module模块,默认不存在需要安装.
`yum -y install mod_ssl`
/etc/httpd/conf.d/ssl.conf            # 配置基于SSL的虚拟主机
/etc/httpd/conf.modules.d/00-ssl.conf # 装载mod_ssl.so模块的指令
/usr/lib64/httpd/modules/mod_ssl.so   # mod_ssl.so的路径
/usr/libexec/httpd-ssl-pass-dialog    # 
/var/cache/httpd/ssl                  # ssl缓存目录,有效期为5分钟
`systemctl reload httpd`              # 重载httpd使生效
2. 创建测试用的私有CA
    cd /etc/pki/CA/
    (umask 077;openssl genrsa -out private/cakey.pem 4096)
    openssl req -new -x509 -key private/cakey.pem -out cacert.pem
    echo 01 > serial
    touch index.txt
    
    cd /etc/httpd; mkdir certs;cd certs
    (umask 077;openssl genrsa -out httpd.key 2048)
    openssl req -new -key httpd.key -out httpd.csr  # 生成证书请求文件
    openssl ca -in httpd.csr -out httpd.crt
3. 编辑/etc/httpd/conf.d/ssl.conf 
    SSLCertificateFile /etc/httpd/certs/httpd.crt
    SSLCertificateKeyFile /etc/httpd/certs/httpd.key
    DocumentRoot "/var/www/html"
    ServerName www.magedu.com:443
4. systemctl httpd reload                           # 此时443端口应该开启了

httpd自带的应用程序

❶ htpasswd: basic认证基于文件实现,用于生成账号和密码的程序
❷ apachectl: httpd自带的报务控制脚本,支持start和stop等命令
❸ apxs: apache 扩展工具
❹ rotatelogs:
❺ ab: apache benchmarking tools

httpd2.2与httpd2.4的不同之处

2.2中的"mpm_prefork_module (static)" 是静态编译的,可在/etc/sysconfig/httpd文件中更改,httpd的启动脚本会调用这个环境文件

2.2的配置文件中MPM的默认配置如下

<IfModule prefork.c>
    StartServers       8         # 初始启动的子进程数量
    MinSpareServers    5         # 最小空闲子进程数量
    MaxSpareServers   20         # 最大空闲子进程数量
    ServerLimit      256         # 子进程数量上限
    MaxClients       256         # 最大并发请求数 其值小于等于ServerLimit
    MaxRequestsPerChild  4000    # 每个子进程服务请求超过4000的话就会被主进程销毁重建
</IfModule>
    
<IfModule worker.c>
    StartServers         4       # 初始启动的子进程数量 worker进程
    MaxClients         300       # 最大并请求数
    MinSpareThreads     25       # 最小空闲线程数量
    MaxSpareThreads     75       # 最大空闲线程数量
    ThreadsPerChild     25       #  每个worker有多少个线程,即启动时有100个线程,但因为上面定义了最大空闲线程为75个所以会自动杀死一个worker子进程.(可实验)
    MaxRequestsPerChild  0       # 每个worker进程最多能处理多少个请求.0表示没有限制
</IfModule>

2.2中基于IP的访问机制的指令与2.4不同,前者使用allow deny等词,后者使用Require

Require all denied|granted       # httpd2.4中(将基于IP与基于用户都用Require指令配置,统一了风格)
Order allow,deny                 # httpd2.2中,由这2行设置
Allow from all

2.2中基于ServerName的虚拟主机,要使用专用指令NameVirtualHost

即在2.2中定义基于ServerName的虚拟主机的话必须在开件开头添加一行如下:
NameVirtualHost IP:PORT
...
否则httpd会有如下错误提示:
[warn] _default_ VirtualHost overlap on port 80, the first has precedence

2.2中对于<Directory >授权没有2.4严格,在2.4中必须对指定的文件做Directory授权才能访问
[1]: http://httpd.apache.org/docs/2.4/mod/mod_log_config.html#formats

上一篇下一篇

猜你喜欢

热点阅读