浅谈http

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了浅谈http相关的知识,希望对你有一定的参考价值。

Web Service
    
    传输层:提供进程地址
        Port number:
            tcp:传输控制协议,面向连接的协议;通信前需要建立虚拟链路;结束后拆除链路;
                0-65535
            udp:User Datagram Protocol,无连接的协议;
                0-65535

        IANA:
            0-1023:众所周知,永久的分配给固定的应用使用,特权端口,22/tcp(ssh), 80/tcp(http), 443/tcp(https)
            1024-41951:亦为注册端口,但要求并不是特别严格,分配给程序注册为某应用使用,11211/tcp, 11211/udp (memcached), 3306/tcp(mysql)
            41952+:客户端程序随机使用的端口;动态端口,或私有端口;其范围的定义:/proc/sys/net/ipv4/ip_local_port_range

    Socket: IPC的一种实现,允许位于不同主机(甚至同一主机)上不同进程之间进行通信;数据交换;Socket API, 1983年,4.2 BSD
        SOCK_STREAM:tcp套接字
        SOCK_DGRAM:udp套接字
        SOCK_RAW: 裸套接字

        IPv4:
            分类:
                A:1-127
                B:128-191
                C:192-223
                D:组播,224-239
                E:240-254

            私有地址:
                A:10.0.0.0/8
                B:172.16.0.0/16-172.31.0.0/16
                C:192.168.0.0/24-192.168.255.0/24

        TCP协议的特性:
            建立连接:三次握手
            将数据打包成段:校验和(CRC-32)
            确认、重传以及超时:
            排序:逻辑序号
            流量控制:滑动窗口算法
            拥塞控制:慢启动和拥塞避免算法

        Socket Domain(根据其所使用的地址):
            AF_INET:Address Family,IPv4
            AF_INET6:IPv6
            AF_UNIX:同一主机上不同进程之间通信时使用;

            每类套接字都至少提供了两种socket:流,数据报
                流:可靠地传递、面向连接、无边界;
                数据报:不可靠地传递、有边界、无连接;

        套接字相关的系统调用:
            socket(): 创建一个套接字;
            bind():绑定
            listen():监听
            accept():接收请求
            connect():请求连接建立
            write():发送
            read():接收
                send(), recv(), sendto(), recvfrom()

    http: hyper text transfer protocol, 80/tcp
        html: 编程语言,超文本标记语言;

        <html>
            <head>
                <title>TITLE</title>
            </head>
            <body>
                <h1></h1>
                    <p> blabla... <a href="http://www.magedu.com/logo.jpg"> blabal </a> </p>
                <h2></h2>
            </body>
        </html>

        CSS: Cascading Style Sheet
        js: javascript

        MIME: Multipurpose Internet Mail Extesion

        工作机制:
            http请求
            http响应

        Web资源:web resource
            静态文件:.jpg, .gif, .html, .txt, .js, .css, .mp3, .avi
            动态文件:.php, .jsp,

            媒体:
                媒体类型(MIME类型):major/minor
                    text/html
                    text/plain
                    image/jpeg
                    image/gif

        URI: Uniform Resource Identifier
            URL: Uniform Resorce Locator,用于描述某服务器某特定资源的位置;
                Scheme://Server:Port/path/to/resource
                    http://www.magedu.com/images/logo.jpg
            URN: Uniform Resource Naming

        http协议版本:
            HTTP/0.9:原型版本,功能简陋
            HTTP/1.0:第一个广泛使用的版本,支持MIME
            HTTP/1.1: 增强了缓存功能
            spdy
            HTTP/2.0:

            rfc

    一次完整的http请求处理过程:
        (1) 建立或处理连接:接收请求或拒绝请求
        (2) 接收请求:
            接收来自于网络的请求报文中对某资源的一次请求的过程;

            并发访问响应模型(Web I/O):
                单进程I/O结构:启动一个进程处理用户请求,而且一次只处理一个;多个请求被串行响应;
                多进程I/O结构:并行启动多个进程,每个进程响应一个请求;
                复用I/O结构:一个进程响应n个请求;
                    多线程模型:一个进程生成N个线程,每个线程响应一个用户请求;
                    事件驱动:event-driven
                复用的多进程I/O结构:启动多个(m)进程,每个进程响应n个请求;


        (3) 处理请求:对请求报文进行解析,并获取请求的资源及请求方法等相关信息

            元数据:请求报文首部
                <method> <URL> <VERSION>
                Host: www.magedu.com   请求的主机名称
                Connection:

        (4) 访问资源:获取请求报文中请求的资源

            web服务器,即存放了web资源的服务器,负责向请求者提供对方请求的静态资源,或动态运行后生成的资源;这些资源放置于本地文件系统某路径下,此路径通常称为DocRoot

            /var/www/html/
                images/1.jpg

            http://www.magedu.com/images/1.jpg

            web服务器资源路径映射方式:
                (a) docroot
                (b) alias
                (c) 虚拟主机docroot
                (d) 用户家目录docroot

        (5) 构建响应报文

            资源的MIME类型:
                显式分类
                魔法分类
                协商分类

            URL重定向:
                web服务构建的响应并非客户端请求的资源,而是资源另外一个访问路径;

        (6) 发送响应报文


        (7) 记录日志

    http服务器程序:
        httpd (apache)
        nginx
        lighttpd

        应用程序服务器:
            IIS
            tomcat, jetty, jboss, resin
            webshpere, weblogic, oc4j

        www.netcraft.com

        httpd的安装配置和使用:
        httpd: apache
            a  patchy server = apache
            ASF: apache software foundation

        httpd的特性:
            高度模块化:core + modules
            DSO: Dynamic Shared Object
            MPM:Multipath Processing Modules
                prefork:多进程模型,每个进程响应一个请求;
                    一个主进程:负责生成n个子进程,子进程也称为工作进程,每个子进程处理一个用户请求;即便没有用户请求,也会预先生成多个空闲进程,随时等待请求到达;最大不会超过1024个;
                worker:多线程模型,每个线程响应一个请求;
                    一个主进程:生成多个子进程,每个子进程负责生个多个线程,每个线程响应一个请求;
                        m进程,n线程:m*n                    
                event:事件驱动模型,每个线程响应n个请求;
                    一个主进程:生成m个子进程,每个进程直接n个请求;
                        m*n

                    httpd-2.2: event为测试使用
                    httpd-.24:event可生产使用

        httpd的功能特性:
            虚拟主机
                IP、Port、FQDN
            CGI:Common Gateway Interface,通用网关接口;
            反向代理
            负载均衡
            路径别名
            丰富的用户认证机制
                basic
                digest
            支持第三方模块

        安装httpd:
            rpm包
            源码编译安装

回顾:
    MPM:
        prefork:多进程模型,一个进程响应一个请求;
        worker:多线程模型(多进程生成,一个进程生成多个线程),一个线程响应一个请求;
        event:事件驱动模型,一个线程响应多个请求;

    并发服务器响应请求:
        单进程I/O模型;
        多进程I/O模型;
        复用的I/O模型;
            多线程模型
            事件驱动
        利用的多进程I/O模型;

httpd(2)
    
    CentOS 6: 2.2
    CentOS 7: 2.4

    安装方式:
        rpm
        编译

    CentOS 6:

        程序环境
            配置文件:
                /etc/httpd/conf/httpd.conf
                /etc/httpd/conf.d/*.conf
            服务脚本:
                /etc/rc.d/init.d/httpd
                配置文件:/etc/sysconfig/httpd
            主程序文件:
                /usr/sbin/httpd
                /usr/sbin/httpd.event
                /usr/sbin/httpd.worker
            日志文件目录:
                /var/log/httpd
                    access_log: 访问日志
                    error_log:错误日志
            站点文档目录:
                /var/www/html
            模块文件路径:
                /usr/lib64/httpd/modules

            配置文件的组成:
                 ~]# grep "Section" /etc/httpd/conf/httpd.conf
                ### Section 1: Global Environment
                ### Section 2: ‘Main‘ server configuration
                ### Section 3: Virtual Hosts

                配置格式:directive value
                    directive: 不区分字符大小写;
                    value: 为路径时,取决于文件系统;

        常用配置:
            1、修改监听的IP和Port
                Listen [IP:]PORT
                例如:

                #Listen 12.34.56.78:80
                    Listen 80
                    Listen 8080
                    Listen 8088

                省略ip表示监听本机所有IP; Listen可重复出现多次;
            
            2、持久连接
                Persistent Connection:连接建立,每个资源获取完成后不会断开连接,而是继续等待其它的请求完成;
                    如何断开?
                        数量限制:100
                        时间限制:可配置
                    副作用:对并发访问量较大的服务器,持久连接功能会使用有些请求得不到响应;
                    折衷:使用较短的持久连接时间;
                        httpd-2.4 支持毫秒级持久时间;
                非持久连接

                KeepAlive On|Off
                MaxKeepAliveRequests #
                KeepAliveTimeout #

                测试:
                    telnet HOST PORT
                    telnet 192.168.0.101 80
                    GET /URL HTTP/1.1
                    Host: HOSTNAME or IP

            3、MPM
                Multipath Process Module:多道处理模块
                    prefork, worker, event

                httpd-2.2不支持同时编译多个模块,所以只能编译时选定一个;rpm安装的包提供三个二进制程序文件,分别用于实现对不同MPM机制的支持;确认方法:

# ps aux  | grep httpd
[[email protected] conf]# ps -ef | grep httpd
root      3495     1  0 05:47 ?        00:00:00 /usr/sbin/httpd
apache    3498  3495  0 05:47 ?        00:00:00 /usr/sbin/httpd
apache    3499  3495  0 05:47 ?        00:00:00 /usr/sbin/httpd
apache    3500  3495  0 05:47 ?        00:00:00 /usr/sbin/httpd
apache    3501  3495  0 05:47 ?        00:00:00 /usr/sbin/httpd
apache    3502  3495  0 05:47 ?        00:00:00 /usr/sbin/httpd
apache    3503  3495  0 05:47 ?        00:00:00 /usr/sbin/httpd
apache    3504  3495  0 05:47 ?        00:00:00 /usr/sbin/httpd
apache    3505  3495  0 05:47 ?        00:00:00 /usr/sbin/httpd
root      3604  3300  0 06:04 pts/7    00:00:00 grep httpd

                默认为/usr/sbin/httpd, 其使用prefork
                    查看模块列表:
                        查看静态编译的模块
                            # httpd -l
                            Compiled in modules:
                              core.c
                              prefork.c
                              http_core.c
                              mod_so.c                      

[[email protected] conf]# httpd -l
Compiled in modules:
  core.c
  prefork.c
  http_core.c
  mod_so.c

                        查看静态编译及动态装载的模块
                            # httpd -M

                更换使用的httpd程序:
                    /etc/sysconfig/httpd
                        HTTPD=
                  #HTTPD=/usr/sbin/httpd.worker


                    重启服务生效; service httpd restart

                prefork的配置:
                    <IfModule prefork.c>
                    StartServers       8
                    MinSpareServers    5
                    MaxSpareServers   20
                    ServerLimit      256
                    MaxClients       256
                    MaxRequestsPerChild  4000
                    </IfModule>                

                worker的配置:
                    <IfModule worker.c>
                    StartServers         4
                    MaxClients         300
                    MinSpareThreads     25
                    MaxSpareThreads     75
                    ThreadsPerChild     25
                    MaxRequestsPerChild  0
                    </IfModule>

                PV, UV
                    PV: Page View
                    UV: User View
                        独立IP量;

                    300*86400=40W+

            4、DSO
                配置指令实现模块加载
                    LoadModule <mod_name> <mod_path>

                    模块路径可使用相对地址
                        相对于ServerRoot(/etc/httpd)指向的路径而言;
                            /etc/httpd/modules/

            5、定义‘Main‘ server的文档页面路径
                DocumentRoot

                文档路径映射:
                    DocumentRoot指向的路径为URL路径的起始位置;
                        DocumentRoot "/var/www/html"
                            test/index.html --> http://HOST:PORT/test/index.html

            6、站点访问控制
                可基于两种类型的路径指明对哪些资源进行访问控制
                    文件系统路径:
                        <Directory ""> </Direcotry>
                        <File ""> </File>
                        <FileMatch ""> </FileMatch>
                    URL路径:
                        <Location ""> </Location>
                        ...

                访问控制机制:
                    基于来源地址;
                    基于账号;

            7、Directory中“基于来源地址”实现访问控制

                (1) Options
                    所有可用特性:Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
                                  None, All
                        Indexes: 索引;
                        FollowSymlinks:允许跟踪符号链接文件;

                (2) 基于来源地址的访问控制机制
                    Order:检查次序
                        Order allow,deny
                        Order deny,allow
                    Allow from
                    Deny from

                    来源地址:
                        IP
                        NetAddr:
                            172.16
                            172.16.0.0
                            172.16.0.0/16
                            172.16.0.0/255.255.0.0

            8、定义默认主页面
                DirecotryIndex index.html index.html.var

            9、日志设定

                错误日志:
                    ErrorLog logs/error_log
                    LogLevel warn

                        debug, info, notice, warn, error, crit, alert, emerg

                访问日志:
                    CustomLog logs/access_log combined
                    LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

                        %h:客户端IP地址;
                        %l: Remote logname (from identd, if supplied). -表示为空;
                        %u: Remote user,  (from auth; may be bogus if return status (%s) is 401);
                        %t:Time the request was received (standard english format),服务器收到请求的时间;
                        %r:First line of request,请求报文的道行信息(method url version);
                        %>s: 响应状态码;
                        %b: 响应报文的大小,单位是字节,不包括响应报文首部;
                        %{Referer}i:请求报文当中"referer"首部的值;当前资源的访问入口,即从哪个页面中的超链接跳转而来;
                        %{User-Agent}i:请求报文当中"User-Agent"首部的值;即发出请求用到的应用程序;

                    详情:http://httpd.apache.org/docs/2.2/mod/mod_log_config.html#formats

            10、路径别名

                DocumentRoot "/www/htocs"
                    http://www.magedu.com/download/bash-4.4.2-3.el6.x86_64.rpm
                        --> /www/htdocs/download/bash-4.4.2-3.el6.x86_64.rpm

                Alias /URL/ "/PATH/TO/SOMEDIR/"    
                
                    Alias /bbs/ "/forum/htdocs"
                        http://www.magedu.com/bbs/index.html     
                            --> /forum/htdocs/bbs/

            11、设定默认字符集
                AddDefaultCharset UTF-8

                GBK, GB2312, GB18030

            12、基于用户的访问控制

                认证质询:
                    WWW-Authenticate:响应码为401,拒绝客户端请求,并说明要求客户提供账号和密码;

                认证:
                    Authorization:客户端用户填入账号和密码后再次发送请求报文;认证通过,则服务器发送响应的资源;

                    认证类型:
                        basic:明文
                        digest:消息摘要

                安全域:需要用户认证后方能访问的路径;
                    应该通过名称对其进行标识,并用于告知用户认证的原因;

                用户的账号和密码存储于何处?
                    虚拟账号:仅用于访问某服务时用到的认证标识;

                    存储:
                        文本文件
                        SQL数据库
                        ldap
                        nis

                basic认证:
                    (1) 定义安全域
                        <Directory "">
                            Options None
                            AllowOverride None
                            AuthType Basic
                            AuthName "STRING"
                            AuthUserFile "/PATH/TO/HTTPD_USER_PASSWD_FILE"
                            Require user username1 username2 ...
                        </Directory>

                            允许账号文件中的所有用户登录访问:
                                Require valid-user

                    (2) 提供账号和密码存储(文本文件)
                        使用htpasswd命令进行管理
                            htpasswd [options] passwordfile username
                                -c: 自动创建passwordfile,因此,仅应该在添加第一个用户时使用;
                                -m: md5加密用户密码;
                                -s: sha1加密用户密码;
                                -D: 删除指定用户

                    (3) 实现基于组进行认证
                        <Directory "">                    
                            Options None
                            AllowOverride None
                            AuthType Basic
                            AuthName "STRING"
                            AuthUserFile "/PATH/TO/HTTPD_USER_PASSWD_FILE"
                            AuthGroupFile "/PATH/TO/HTTPD_GROUP_FILE"
                            Require group GROUP1 GROUP2 ...
                        </Directory>    

                        要提供:用户账号文件和组文件;

                            组文件:每一行定义一个组
                                GRP_NAME:user1 user2 user3 ...


                        示例:
                            <Directory "/www/htdocs/admin">
                                Options None
                                AllowOverride None
                                AuthType Basic
                                AuthName "Administator private"
                                AuthUserFile "/etc/httpd/conf.d/.htpasswd"
                                AuthGroupFile "/etc/httpd/conf.d/.htgroup"
                                Require group webadmin
                            </Directory>

            13、虚拟主机

                有三种实现方案:
                    基于ip:
                        为每个虚拟主机准备至少一个ip地址;
                    基于port:
                        为每个虚拟主机准备至少一个专用port;实践中很少使用;
                    基于hostname:
                        为每个虚拟主机准备至少一个专用hostname;

                    可混合使用上述三种方式中任意方式;

                注意:一般虚拟主机莫与中心主机混用,所以,要使用虚拟主机,先禁用中心主机;
                    禁用中心主机:注释DocumentRoot
               
               mkdir -pv /vhosts/{web1,web2,web3,web4}/htdocs
               web1
               web2

[[email protected] ~]#  ip addr add 192.168.1.102/24 dev eth1
[[email protected] ~]# ip addr list
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:3d:18:68 brd ff:ff:ff:ff:ff:ff
    inet 192.168.0.101/24 brd 192.168.0.255 scope global eth1
    inet 192.168.1.102/24 scope global eth1
    inet6 fe80::20c:29ff:fe3d:1868/64 scope link 
       valid_lft forever preferred_lft forever

       
                每个虚拟主机都有专用配置:
                    <VirtualHost "IP:PORT">
                        SeverName
                        DocumentRoot ""
                    </VirtualHost>

                        ServerAlias: 虚拟主机的别名;
                        ErrorLog
                        CustomLog
                        <Directory "">
                        </Directory>

                示例1:基于ip
<VirtualHost 172.16.100.6:80>
    ServerName web1.magedu.com
    DocumentRoot "/vhosts/web1/htdocs"
</VirtualHost>

<VirtualHost 172.16.100.7:80>
    ServerName web2.magedu.com
    DocumentRoot "/vhosts/web2/htdocs"
</VirtualHost>

http -t  
测试语法:  service  httpd configtest

                示例2:基于port
                    <VirtualHost 172.16.100.7:80>
                        ServerName web2.magedu.com
                        DocumentRoot "/vhosts/web2/htdocs"
                    </VirtualHost>

                    <VirtualHost 172.16.100.7:8080>
                        ServerName web3.magedu.com
                        DocumentRoot "/vhosts/web3/htdocs"
                    </VirtualHost>

示例3:基于hostname

[[email protected] ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.0.101    crxy97    web1.magedu.com    web2.magedu.com    web3.magedu.com
192.168.0.102  crxy98
192.168.0.103  crxy99

<VirtualHost 172.16.100.6:80>
    ServerName web1.magedu.com
    DocumentRoot "/vhosts/web1/htdocs"
</VirtualHost>

<VirtualHost 172.16.100.6:80>
    ServerName web2.magedu.com
    DocumentRoot "/vhosts/web2/htdocs"
</VirtualHost>

<VirtualHost 172.16.100.6:80>
    ServerName web3.magedu.com
    DocumentRoot "/vhosts/web3/htdocs"
</VirtualHost>

[[email protected] ~]# curl http://web2.magedu.com
web2
[[email protected] ~]# curl http://web1.magedu.com
web1
[[email protected] ~]# curl http://web3.magedu.com
web3

            14、内置的status页面
                <Location /server-status>
                    SetHandler server-status
                    Order deny,allow
                    Deny from all
                    Allow from 172.16
                </Location>    
                
实现:基于账号实现访问控制

<VirtualHost 192.168.0.101:80>
        ServerName crxy97
        DocumentRoot "/vhosts/web1/htdocs"
</VirtualHost>

<VirtualHost 192.168.0.102:80>
        ServerName crxy98
        DocumentRoot "/vhosts/web2/htdocs"
</VirtualHost>

<VirtualHost 192.168.0.102:8080>
        ServerName crxy98
        DocumentRoot "/vhosts/web3/htdocs"
</VirtualHost>

本文出自 “梁小明的博客” 博客,请务必保留此出处http://7038006.blog.51cto.com/7028006/1855194

以上是关于浅谈http的主要内容,如果未能解决你的问题,请参考以下文章

HTTP客户端代码片段

浅谈svn

浅谈Ajax 异步的几点细节

高效Web开发的10个jQuery代码片段

Flutter 报错 DioError [DioErrorType.DEFAULT]: Bad state: Insecure HTTP is not allowed by platform(代码片段

如何从一个片段导航到另一个片段?