HTTP服務

HTTP:HyperText Transfer Protocol,超文件傳輸協議

上世紀90年代初,誕生於量子實驗室

    http/09版本:僅支持純文件(超連接),ASCII

    HTML:編寫超文本的語言  ,HyperText mark Language

URI:統一資源標識符,Uniform Resource Indentifier 

    URL:是URI的一個子集,Uniform resource locater


HTTP資源獲取的方法:(method)

    1、GET(0.9版本)

    2、PUT,POST DELETE(1.0版本)HEAD(只返回首部,不返回主體)trace options connection


MIME機制:Multipurpose Internet Mail extension,多用途互聯網郵件擴展

    MIME:將非文件數據在傳輸前重新編碼爲文件格式再傳輸。接收方能夠用相反的方式將其重新還原爲        原來的格式,還能夠調用相應的程序來打開此文件


SMTP:Simple mail transmission protocol


動態網頁:在服務器端存儲的文檔非HTML格式,而是編程語言開發的腳本,腳本接受參數之後在服務器運行一次,運行完成後會生成HTML格式文檔,把生成的文檔發給客戶端


HTTP客戶端數據報文

    1、包含IP協議信息

        source IP

        destination IP

    2、TCP協議信息

        source port

        destination port

    3、http協議信息

        GET /file.html

        Host:www.btsbox.com(WEB虛擬主機機制,所以有添加此信息)


請求報文語法

<method> <request-URL><version>   # 獲得方法 請求的資源 http版本

<headers> #http協議首部

              #空白行

<entity-body> #報文主體

              #空白行

響應報文語法

<version> <status><reason-phrase>  #http版本  狀態碼 成功或失敗的解釋

<headers>    #響應報文首部

             #空白行

<entity-body>

             #空白行


狀態代碼:

    1XX:純信息

    2XX:成功類的狀態信息

    3XX:重定向類的信息(301永久重定向,302臨時重定向,304內容沒有發生改變,使用本地緩存)

    4XX:客戶端錯誤類的信息(404不存在的文件)

    5XX:服務器端錯誤類的信息


報文示例

請求報文:

GET / HTTP/1.1          #說明協議 和請求的路徑 "/"一般爲主頁

Host:www.mageedua.com   #報文首部都是以HOST:這類格式出現,既以這類格式出現的,都爲報文首部

Connection:keep-aliv    #連接方式爲長連接,不斷開連接

                        #空白行

響應報文:

HTTP/1.1 200 OK   #返回成功狀態碼

X-powered-By:PHP/5.2.17 #說明是一個PHP動態網頁

Vary:Accep-Encodeing,cookie,User-Agent

Cache-Control:max-age=3,must-revalidate

Content-Encoding:gzip   #網頁壓縮技術

Content-Length:6931     #網頁長度 

                        #空白行


上面兩個報文的第一行通常稱作報文“起始行(start line)",後面的標籤格式的內容稱作首部域(Header field),每個首部域都由名稱(name)和值(value)組成,中間用逗號分隔。另外,響應報文通常還有一個稱作body的信息主體,即響應給客戶端的內容


web服務器的主要操作

1、建立連接-->接受或拒絕客戶端連接請求

2、接收請求-->通過網絡讀取HTTP請求報文

3、處理請求-->解析請求報文並做出相應的動作

4、訪問資源-->訪問請求報文中相應的資源

5、構建響應-->使用正確的首部生成http響應報文

6、發送響應-->向客戶端發送生成的響應報文

7、記錄日誌--當已經完成的http事務記錄進日誌文件


http/1.1

    增強了緩存功能、

    引入了長連接機制


長連接機制:

    空閒超時

    請求次數限制

WEB服務器模型:

單進程/單線程服務器模型

多進程/多線程服務器模型

事件驅動、狀態通知服務器模型

多進程、響應多請求服務器模型

MPM:Multi path Modules (多道處理模塊)

    prefork(一個請求用一個進程響應)

    work(一個請求用一個線程響應,啓動多個進程,每個進程生成多個線程)

    event(一個進程響應多個請求,基於事件處理模型)

    winnt

Server soft:

    httpd

    IIS

    nginx

    lighttpd

    thttpd


應用程序服務器

    IIS

    tomcat(apache,JSP,open source)

    websphere(IBM,JSP,commodity)

    weblogic(Oracle,JSP,commodity)

    JBoss(Readhat,open source,commodity,核心是tomcat)


Apache

ASF:Apache software Foundation


httpd:

    web server, Open source

    version: 2.2 2.4


httpd特性:

    事先創建進程

    按需維持適當的進程

    模塊設計,核心比較小,各種功能都通過模塊添加(包括PHP)

        支持運行時配置,支持單獨編譯模塊

    支持多種方式的虛擬主機配置

         虛擬主機:

                基於IP的虛擬主機

                基於端口的虛擬主機

                基於域名的虛擬主機

    支持https協議(mod_ssl)

    支持用戶認證

        簡單認證

        摘要認證

        基於表單認證

    訪問控制機制

        基於IP或主機名的訪問控制機制 

        基於每目錄的訪問控制

    支持URL重寫


httpd: SELinux(事先讓其處於permssive,disabled)

httpd進程:

    /usr/sbin/httpd(MPM:prefork)

        httpd: root,root (master process)

        httpd: apache,apache (worker process)

    /etc/rc.d/init.d/httpd (服務腳本)

httpd 端口:

    80/tcp, 443/tcp

httpd工作目錄

    /etc/httpd:工作根目錄,相當於程序安裝目錄

    /etc/httpd/conf:配置文件目錄

        主配置文件:httpd.conf

        /etc/httpd/conf.d/*.conf :是對httpd.conf的分割

    /etc/httpd/moduless:模塊目錄

    /etc/httpd/logs --> /var/log/httpd:日誌目錄

        日誌文件有兩類:訪問日誌access_log,錯誤日誌:err_log

    /var/www:網站存儲位置

        html:靜態網站存儲位置

        cgi-bin:動態網站存儲位置

        cgi:可以讓httpd調用其他程序的一種機制,Common Gateway Interface

            cgi:Client-->httpd(index.cgi)-->Spwan process(Index.cgi)-->httpd-->Client

                http以index.cgi文件中指定的程序調用程序轉換,如在bash腳本的 #!/bin/bash

            fastcgi:當用戶請求動態網頁,http將請求直接傳遞給cgi的子進程運行,這樣可以實                        現靜態網頁服務與動態服務物理分離。

    /etc/httpd/conf/magic:定義如何識別MIME格式的文檔

LAMP:apache+mysql+php


httpd的測試工具:

LoadRunner:專業級的HTTP性能測試工具


httpd的安裝

[root@Centos6 dnstop-20140915]# yum install httpd


http.conf配置文件說明:

    格式:directive value,指令不區分大小寫, value則可能要區分大小寫

ServerTokens OS    #顯示web的信息,可以接受多個參數
KeepAlive Off   #是否打開長連接
MaxKeepAliveRequests 100 #請求的資源數
KeepAliveTimeout 15  #長連接的超時時間
# prefork MPM  #定義MPM工作模型參數
# StartServers: number of server processes to start
# MinSpareServers: minimum number of server processes which are kept spare
# MaxSpareServers: maximum number of server processes which are kept spare
# ServerLimit: maximum value for MaxClients for the lifetime of the server
# MaxClients: maximum number of server processes allowed to start
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule prefork.c>   #perfork模型參數
StartServers       8    #啓動進程數
MinSpareServers    5    #最小空閒進程
MaxSpareServers   20    #最大空閒進程
ServerLimit      256    #MaxClients的上限值,調整需先殺死所有進程,再設置啓動,方生效
MaxClients       256    #最大客戶端數
MaxRequestsPerChild  4000  #每個子進程最多響應多少用戶請求
</IfModule>
# worker MPM        
# StartServers: initial number of server processes to start
# MaxClients: maximum number of simultaneous client connections
# MinSpareThreads: minimum number of worker threads which are kept spare
# MaxSpareThreads: maximum number of worker threads which are kept spare
# ThreadsPerChild: constant number of worker threads in each server process
# MaxRequestsPerChild: maximum number of requests a server process serves
<IfModule worker.c>
StartServers         4    #啓動的進程數
MaxClients         300    #最大的客戶端
MinSpareThreads     25    #最小線程數
MaxSpareThreads     75    #最大線程
ThreadsPerChild     25    #每個進程啓動的線程數
MaxRequestsPerChild  0    #每個進程的最大請求
</IfModule>
#Listen 12.34.56.78:80
Listen 80    #監聽所有IP的80端口
# Dynamic Shared Object (DSO) Support   #加載的模塊
#
# To be able to use the functionality of a module which was built as a DSO you
# have to place corresponding `LoadModule' lines at this location so the
# directives contained in it are actually available _before_ they are used.
# Statically compiled modules (those listed by `httpd -l') do not need
# to be loaded here.
#
# Example:
# LoadModule foo_module modules/mod_foo.so
#
LoadModule auth_basic_module modules/mod_auth_basic.so
LoadModule auth_digest_module modules/mod_auth_digest.so
LoadModule authn_file_module modules/mod_authn_file.so
LoadModule authn_alias_module modules/mod_authn_alias.so
LoadModule authn_anon_module modules/mod_authn_anon.so
LoadModule authn_dbm_module modules/mod_authn_dbm.so
LoadModule authn_default_module modules/mod_authn_default.so
LoadModule authz_host_module modules/mod_authz_host.so
LoadModule authz_user_module modules/mod_authz_user.so
LoadModule authz_owner_module modules/mod_authz_owner.so
LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
LoadModule authz_dbm_module modules/mod_authz_dbm.so
LoadModule authz_default_module modules/mod_authz_default.so
LoadModule ldap_module modules/mod_ldap.so

# Load config files from the config directory "/etc/httpd/conf.d".
#
Include conf.d/*.conf    #加載的配置文件
 If you wish httpd to run as a different user or group, you must run
# httpd as root initially and it will switch.  
#
# User/Group: The name (or #number) of the user/group to run httpd as.
#  . On SCO (ODT 3) use "User nouser" and "Group nogroup".
#  . On HPUX you may not be able to use shared memory as nobody, and the
#    suggested workaround is to create a user www and use that user.
#  NOTE that some kernels refuse to setgid(Group) or semctl(IPC_SET)
#  when the value of (unsigned)Group is above 60000; 
#  don't use Group #-1 on these systems!
#
User apache        #httpd啓動的用戶
Group apache        #httpd啓動的組

#主服務模式 Section 2
# ServerAdmin: Your address, where problems with the server should be
# e-mailed.  This address appears on some server-generated pages, such
# as error documents.  e.g. [email protected]
#
ServerAdmin root@localhost  #網站管理員聯繫方式
#ServerName  #主機地址, 如果沒有在DNS中指定,會反解IP所對應的FQDN 
DocumentRoot "/var/www/html"  #網頁存放路徑
<Directory />
    Options FollowSymLinks   #Options定義的屬性可以爲多個, 彼此使用空格隔開
    AllowOverride None        #允許覆蓋,覆蓋下面Order的功能
        Order allow,deny    #Order用於定義基於主機訪問功能的,IP,網絡地址或主機定義訪問                              控制
    Allow from all
</Directory>        #定義Document的訪問屬性
#Options屬性:
    Index:定義索引,索引是指列出目錄下所有的文件
    None:不支持任何選項
    FollowSymLinks:跟隨符號連接,意味訪問符號連接所指向的文件,會降低服務器的性能
    Includes:允許執行服務器端包含(SSI),此方式不安全
    SymLinksifOwnerMatch:允許執行符號連接,但屬主必須與執行httpd進程的屬主相匹配,不                               開放
    ExecCGI:允許執行CGI腳本
    MultiViews:判斷客戶端使用的語言,並顯示相應語言的網頁,一般比較消耗資源
    ALL:啓用所有選項
# UserDir: The name of the directory that is appended onto a user's home
# directory if a ~user request is received. 
#
# The path to the end user account 'public_html' directory must be
# accessible to the webserver userid.  This usually means that ~userid
# must have permissions of 711, ~userid/public_html must have permissions
# of 755, and documents contained therein must be world-readable.
# Otherwise, the client will only receive a "403 Forbidden" message.
# of 755, and documents contained therein must be world-readable.
# Otherwise, the client will only receive a "403 Forbidden" message.
#
# See also: http://httpd.apache.org/docs/misc/FAQ.html#forbidden
#
<IfModule mod_userdir.c>  #此模塊允許用戶是否可以在自己的目錄建立各種的網頁文件
    #
    # UserDir is disabled by default since it can confirm the presence
    # of a username on the system (depending on home directory
    # permissions).
    #
    UserDir disabled  #默認關閉

    #
    # To enable requests to /~user/ to serve the user's public_html
    # directory, remove the "UserDir disabled" line above, and uncomment
    # the following line instead:
    # 
    #UserDir public_html  #如果需要啓用,註釋disabled項,開啓此啓,會在用戶的家目錄                                    中建立一個public_html文件,讓用戶存放各種網頁文件
#啓用此項後,需在用戶的家目錄(系統用戶)中建立public_html文件夾,再創建各種的html文檔,但需要讓用戶的家目錄具有其他用戶可執行的權限,方可以網址http://10.189.9.202/~hadoop的方式訪問

</IfModule>

#
# Control access to UserDir directories.  The following is an example
# for a site where these directories are restricted to read-only.
#
#<Directory /home/*/public_html>   #定義用戶的家目錄權限認證
#    AllowOverride FileInfo AuthConfig Limit
#    Options MultiViews Indexes SymLinksIfOwnerMatch IncludesNoExec
#    <Limit GET POST OPTIONS>    #限定訪問方法,使用GET POST OPTIONS
#        Order allow,deny
#        Allow from all        #以上三種方法,所有用戶都可訪問
#    </Limit>
#    <LimitExcept GET POST OPTIONS>    #除這三種方法
#        Order deny,allow
#        Deny from all                #全部拒絕
#    </LimitExcept>
#</Directory>

DirectoryIndex index.html index.html.var   #主頁的文件名稱

AccessFileName .htaccess    #定義網站的每個目錄的訪問權限,需把規則放到目錄下的以.htacces                            s文件中, 如使用用戶名和密碼規則,但非常影響apache的執行效率
                            子目錄對父目錄的權限是繼承的。所以性能會受影響
<Files ~ "^\.ht">    #匹配以.ht所有的文件的權限,~表示匹配
    Order allow,deny
    Deny from all
    Satisfy All
</Files>  

TypesConfig /etc/mime.types   #支持哪此類型的二進制文件,這裏指定mime類型的文件       
DefaultType text/plain    #默認文件類型爲純文本類型

<IfModule mod_mime_magic.c>   #判斷mod_mime_magic.c模塊存在,文件位置在以下路徑中
#   MIMEMagicFile /usr/share/magic.mime
    MIMEMagicFile conf/magic
</IfModule>

HostnameLookups Off  #記錄訪問日誌中,關閉記錄主機名,只記錄IP,以提升效率

#EnableMMAP off
#EnableMMAP off
ErrorLog logs/error_log  #定義的錯誤日誌
LogLevel warn   #日誌級別爲warnning

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %b" common  #common表示通用模式
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

#定義訪問日誌的格式,每個%表示定義的了個宏,%h:客戶端地址,%l:以哪個用戶的身份,%u:登陸網站所使用的用戶,%t:什麼時間,\"%r\":訪問的方法,%>s:最後一次請求的狀態碼,%b:響應報文的大小,\"%{Referer}i:顯示訪問的時候從哪個連接來的,比如從一個頁面中的連接跳到目錄頁面,\"%{User-Agent}i\":客戶端瀏覽器類型
#CustomLog logs/access_log common   #訪問日誌文件位置,並以混合模式記錄

ServerSignature On

Alias /icons/ "/var/www/icons/"  #定義訪問別名,icons爲別名,/var/www/icons爲系統真實路徑

<Directory "/var/www/icons">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order allow,deny
    Allow from all
</Directory>


<Location /server-status>    #服務器的狀態信息,可以使用IE在URL後添加server-status查看
    SetHandler server-status
    Order deny,allow
    Deny from all
   Allow from 10.189.8.26
</Location>

criptAlias /cgi-bin/ "/var/www/cgi-bin/"  #在哪個目錄下可以執行CGI腳本
<Directory "/var/www/cgi-bin">  
    AllowOverride None
    Options None
    Order allow,deny
    Allow from all
</Directory>



修改HTTP運行模型

[root@Centos6 conf.d]# httpd -l   #查看httpd支持的模型
Compiled in modules:
  core.c
  prefork.c
  http_core.c
  mod_so.c
  [root@Centos6 conf.d]# httpd.event -l  
Compiled in modules:
  core.c
  event.c
  http_core.c
  mod_so.c
[root@Centos6 conf.d]# httpd.worker -l
Compiled in modules:
  core.c
  worker.c
  http_core.c
  mod_so.c
[root@Centos6 conf.d]# vim /etc/sysconfig/httpd   #啓用worker模型
  HTTPD=/usr/sbin/httpd.worker

httpd配置文件語法檢查:

[root@Centos6 ~]# httpd -t
Syntax OK

elinks:純文件網頁瀏覽工具

    -dump:打開網頁,立即退出

    -source:顯示網頁的源碼


httpd網頁的用戶認證

  1、基於主機的用戶認證

<Directory "/var/www/html">
    AllowOverride None   #None,表示基於主機IP的認證機制
    Order allow,deny
    Allow from all
</Directory>
#Order 示例
    Order allow,deny
    allow form 192.168.0.0/24   
    #只允許這個網段的主機訪問,其他的都deny
    Order deny,allow
    deny form 129.168.0.0/24
    #拒絕這個網段的主機訪問,其他都允許
    Order deny,allow
    deny form 192.168.0.11 192.168.0.12
    #只拒絕這兩個主機訪問網站,其他都允許 
#地址的表現方式:
    IP
    network/netmask
    HOSTNAME:
    Domainname:a.com 
    Partial IP : 172.16,172.16.0.0/16

 2、基於用戶和組的用戶認證

<Directory "/var/www/html">
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
   AllowOverride AuthConfig    #AuthConfig指定使用配置文件驗證用戶方式
        AuthType Basic        #認證方式爲Basic模式,還有digest模式認證
        AuthName "請輸入用戶名和密碼"    #輸入用戶密碼框的提示
        AuthUserFile "/usr/local/apache/htpasswd"  #存放用戶的文件路徑
        AuthGroupFile "/usr/local/apache/htgroup"  #存放組的文件路徑
        Require valid-user    #指定在存放用戶文件中的哪此文件可以訪問,valid-user表示所有
        Require user hadoop   #表示只有在文件中的hadoop用戶可以訪問
        
            Order allow,deny
    Allow from all
</Directory>
#使用htpasswd命令建立站點訪問的用戶,htpasswd表示使用Basic認證模式,也可以使用htdigest命令建立用戶,表示認證模式爲digest模式
[root@Centos6 ~]# htpasswd  -c -m /usr/local/apache/htpasswd hadoop  
New password: 
Re-type new password: 
Adding password for user hadoop
#htpasswd -c -m :c表示創建認證文件,-m表示加密使用md5
#htpasswd -D :表示刪除一個用戶
[root@Centos6 www]# cat /usr/local/apache/htpasswd 
hadoop:$apr1$.Znxpwih$wCoylwMZfbrg0irYJ4Br70  #apr1表示加密模式
#認證組文件的建立
[root@Centos6 www]# cat  /usr/local/apache/htgroup 
httpd: hadoop readhat   #httpd是組名, hadoop readhat爲用戶

#基於數據庫存取用戶名的認證方式
<Directory /www/docs/private>
AuthName "Private"
AuthType Basic
AuthBasicProvider dbm
AuthDBMUserFile /www/passwords/passwd.dbm
Require valid-user
</Directory>
#以上配置完成,需使用htdbm命令創建DBM認證文件

查看http加載的額外模塊

[root@Centos6 www]# httpd -M   
httpd: apr_sockaddr_info_get() failed for Centos6.6A
httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName
Loaded Modules:
 core_module (static)
 mpm_prefork_module (static)
 http_module (static)
 so_module (static)
 auth_basic_module (shared)


DocumentRoot /www/baidu.com/
<directory "www/baidu.com">
    option
    AllowOverride
</directory>   #此directory容器是定義/www/biadu.com,他是一個路徑,是定義訪問文件的權限

<location "/p_w_picpaths">

</location>  #location容器是定義URL的訪問路徑目錄

apache虛擬主機的定義:


<VirtualHost HOST>  

    Option

    ...

</VirtualHost>

    注:需使用虛擬主機,必須先註銷中心主機,方法:註釋DocumentRoot


host的格式:

    ip1:80

    ip2:80

基於端口:

    IP:80

    IP:8080

基於域名:

    *.80

示例如下

#修改/etc/httpd/conf/httpd.conf文件中的DocumentRoot,將其註釋
#DocumentRoot "/var/www/html"
#將需要使用的端口在/etc/httpd/conf/httpd.conf文件中開啓
Listen 80
Listen 8080
#將虛擬主機功能開啓,修改httpd.conf文件配置
NameVirtualHost 10.189.9.203:80 
#表示在此IP上開啓基於域名的虛擬主機,如果是所有IP,使用*:80 

#建立虛擬主機:
[root@Centos6 ~]# cat  /etc/httpd/conf.d/virtual.conf  #也可以直接在httpd.conf中添加
<VirtualHost _default_:80>   #定義默認訪問主頁,匹配一般從上往下匹配虛擬主機
        DocumentRoot "/www/default80"
        # ...
</VirtualHost>
<VirtualHost _default_:*>
        DocumentRoot "/www/default"
        # ...
</VirtualHost>
<VirtualHost 10.189.9.202:80>
   ServerName www.a.com
   DocumentRoot "/www/a.com"
</VirtualHost>

<VirtualHost 10.189.9.202:8080>
  ServerName www.b.com
  DocumentRoot "/www/b.com"
</VirtualHost>

<VirtualHost 10.189.9.203:80>
 ServerName wwww.c.com
  DocumentRoot "/www/c.com"
  <Directory "/www/c.com">    #定義c.com基於主機的訪問規則,其拒絕10.189.8.26
        options none
        AllowOverride none
        Order deny,allow
        Deny from 10.189.8.26
  </Directory>
</VirtualHost>

<VirtualHost 10.189.9.203:80>
 ServerName   www.d.com
 DocumentRoot "/www/d.com"
 CustomLog /var/log/httpd/a.com/access_log combined
 ErrorLog /var/log/httpd/a.com/error_log
 LogLevel warn
   <Directory /www/d.com>
        Options none
        AllowOverride authconfig
        AuthType basic
        AuthName "Restrict area"
        AuthUserFile "/www/d.com/.htpasswd"
        Require valid-user
   </Directory>
</VirtualHost>

[root@Centos6 ~]# cat /www/a.com/index.html  #建立虛擬主機的網頁目錄及index.html文件
<title>A.com</title>
<h1>This is a.com site.</h1>
[root@Centos6 ~]# cat /www/b.com/index.html 
<title>B</title>
<h1>This is b.com site.</h1>
[root@Centos6 ~]# cat /www/c.com/index.html 
<title>C</title>
<h1>This is c.com site.</h1>
[root@Centos6 ~]# cat /www/d.com/index.html 
<title>D</title>
<h1>This is d.com site.</h1>


搭建https站點

#首先配置apache的虛擬主機配置
[root@localhost ssl]# vim /etc/httpd/conf/httpd.conf
#DocumentRoot "/var/www/html"  #關閉主網站功能
NameVirtualHost 10.189.9.202:80   #開啓虛擬主機功能
[root@localhost ssl]# cat /etc/httpd/conf.d/virtual.conf 
<VirtualHost 10.189.9.202:80>
	ServerName www.a.com
	DocumentRoot "/www/a.com"
	CustomLog /var/log/httpd/a.com/access_log combined
	ErrorLog /var/log/httpd/a.com/Error_log
	LogLevel warn
</VirtualHost>
#新建虛擬主機的日誌文件夾,文件會自動建立
#建立CA
[root@localhost CA]# (umask 077;openssl genrsa -out private/cakey.pem 2048)  #生成CA私鑰
Generating RSA private key, 2048 bit long modulus
................................................+++
..+++
e is 65537 (0x10001)
#生成自簽證書
[root@localhost CA]# (umask 077;openssl req -new -x509 -key private/cakey.pem -out cacert.pem -days 3657)
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [CN]:
State or Province Name (full name) [ShangHai]:
Locality Name (eg, city) [ShangHai]:
Organization Name (eg, company) [ogilvy]:
Organizational Unit Name (eg, section) [Tech]:
Common Name (eg, your name or your server's hostname) []:ogilvy.com  
Email Address []:[email protected]
root@localhost CA]# touch index.txt
[root@localhost CA]# touch serial
[root@localhost CA]# echo 01 >> serial

#在請求籤證書的服務器端生成簽署請求,首先生成私鑰
[root@localhost ssl]# mkdir ssl #生成私鑰及證書的存放路徑
[root@localhost ssl]# openssl genrsa -out cakey.pem 1024  #生成私鑰
[root@localhost ssl]# openssl req -new -key cakey.pem -out cacert.csr -days 3655 #導出籤                                                                        署請求,即導出公鑰
[root@localhost ssl]# scp cacert.csr [email protected]:/tmp/ #傳送簽署請求文件到CA服務器

#在CA服務器上籤署證書
[root@localhost tmp]# openssl ca -in cacert.csr -out cacert.pem
Using configuration from /etc/pki/tls/openssl.cnf
Check that the request matches the signature
Signature ok
Certificate Details:
        Serial Number: 1 (0x1)
        Validity
            Not Before: Jun 15 20:18:22 2015 GMT
            Not After : Jun 14 20:18:22 2016 GMT
        Subject:
            countryName               = CN
            stateOrProvinceName       = ShangHai
            organizationName          = ogilvy
            organizationalUnitName    = Tech
            commonName                = www.a.com
            emailAddress              = [email protected]
        X509v3 extensions:
            X509v3 Basic Constraints: 
                CA:FALSE
            Netscape Comment: 
                OpenSSL Generated Certificate
            X509v3 Subject Key Identifier: 
                4D:B9:D2:76:8F:53:F5:8A:05:1F:8C:71:E9:24:46:3C:34:DA:FB:DE
            X509v3 Authority Key Identifier: 
                keyid:75:B0:94:8A:2B:20:15:D4:08:43:20:89:EE:8B:2C:45:80:BF:5A:F8

Certificate is to be certified until Jun 14 20:18:22 2016 GMT (365 days)
Sign the certificate? [y/n]:y


1 out of 1 certificate requests certified, commit? [y/n]y
Write out database with 1 new entries
Data Base Updated

#將簽署的證書發送給服務器
[root@localhost tmp]# scp cacert.pem [email protected]:/etc/httpd/ssl/

#安裝httpd的ssl支持模塊
[root@localhost tmp] yum install mod_ssl
[root@localhost conf]# rpm -ql mod_ssl   #查看mod_ssl的配置文件
/etc/httpd/conf.d/ssl.conf
/usr/lib64/httpd/modules/mod_ssl.so
/var/cache/mod_ssl
/var/cache/mod_ssl/scache.dir
/var/cache/mod_ssl/scache.pag
/var/cache/mod_ssl/scache.sem

#配置ssl服務
[root@localhost conf]# grep -v "^#" ../conf.d/ssl.conf | sed '/^$/d'
LoadModule ssl_module modules/mod_ssl.so
Listen 443    #監聽443端口
SSLPassPhraseDialog  builtin
SSLSessionCache         shmcb:/var/cache/mod_ssl/scache(512000)
SSLSessionCacheTimeout  300
SSLMutex default
SSLRandomSeed startup file:/dev/urandom  256
SSLRandomSeed connect builtin
SSLCryptoDevice builtin
<VirtualHost 10.189.9.202:443>
ServerName     #配置針對哪個域名的虛擬主機設置,https只能對一個IP的一個域名開啓 
DocumentRoot "/www/a.com"
ErrorLog logs/ssl_error_log
TransferLog logs/ssl_access_log
LogLevel warn
SSLEngine on   #開啓https功能,必須on
SSLProtocol all -SSLv2 #開啓所有ssl協議,但不支持sslv2
SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM:+LOW #支持所有加密算法,但不                                                                    支持ADH EXPORT SSLV2
SSLCertificateFile /etc/httpd/ssl/cacert.pem  #證書文件路徑
SSLCertificateKeyFile /etc/httpd/ssl/cakey.pem #私鑰存放目錄
<Files ~ "\.(cgi|shtml|phtml|php3?)$">
    SSLOptions +StdEnvVars
</Files>
<Directory "/var/www/cgi-bin">
    SSLOptions +StdEnvVars
</Directory>
SetEnvIf User-Agent ".*MSIE.*" \
         nokeepalive ssl-unclean-shutdown \
         downgrade-1.0 force-response-1.0
CustomLog logs/ssl_request_log \
          "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"
</VirtualHost>  

#導出CA的公鑰到客戶端,即可使用https://www.a.com訪問網站


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章