第十七周作業(yè)

1糖埋、nginx負載均衡中常見的算法及原理有哪些瞳别?

  • RR:輪詢

  • WRR:加權輪詢

  • least_time header | last_byte [inflight];

    • 考量服務器權重的前提下,將新的請求調度給最低平均響應時間和最少活動連接數的后端服務器馆铁;有多臺都符合時就執(zhí)行wrr历谍;

    • 如果指定了header望侈,則response header的響應時間用來評估($upstream_header_time);如果指定了last_byte岂丘,則完整的response的響應時間用來評估($upstream_response_time);

    • 如果指定了inflight寨蹋,則未完成的請求也作為評估條件

  • radom [two [method]]

    • 考量服務器權重的前提下,將新請求按照隨機方式調度給后端服務器組运褪;

    • 如果指定了two參數秸讹,則每次隨機算法選中兩臺服務器,然后根據method指定的算法在這兩臺服務器中選中一臺劣欢,默認的method是least_conn

  • least_conn;

    • 考量服務器權重的前提下,將新的請求調度給由最少連接數量的后端服務器丸相;如果這樣的服務器有多臺灭忠,就執(zhí)行wrr方式調度涕蜂;
  • ip_hash

    • 新請求按照客戶端的IP地址來調度,IPv4前三個8位組有鹿,或者整個IPv6地址將作為hash key葱跋,確保請求來自相同客戶端將總是被調度給相同的服務器,除非這臺服務器失效荠卷。
  • hash KEY

    • 基于定義的KEY值執(zhí)行HASH運算得到HASH值,key可以是文本,變量或者兩者的結合社牲,用這個值取模總權重熟空,根據結果,歸類到某一臺后端服務器上

    • 如果服務器出現增加或者刪除時迈喉,將導致總權重值發(fā)生變化挨摸,原來調度給A服務器的會話都可能分散到其他服務器膝蜈,導致之前的緩存失效

  • hash KEY consistent

    • 執(zhí)行ketama一致性hash算法,而不是僅通過hash值去判斷服務器窍帝;

    • 一致性hash算法將整個hash空間組織成一個虛擬的圓環(huán),假設hash函數H的值空間是0到(232)-1深浮,整個空間按順時針方向組織飞苇,0和232-1在零點鐘方向重合。

    • 將服務器的信息忿等,比如IP或主機名作為KEY贸街,與H執(zhí)行取模運算,得到的值一定會落在這個圓環(huán)的某一點上脓鹃,這樣每臺服務器就確定了在HASH圓環(huán)上的位置渐白。

    • 將用戶的請求也通過相同的方式纯衍,與H執(zhí)行取模運算,同樣得到一個落在圓環(huán)上的值歌亲,這個圓環(huán)上的值在圓環(huán)上順時針運動陷揪,遇到的第一臺服務器就是請求被調度到的服務器;

    • 如果服務器過少時飞蚓,可能導致服務器執(zhí)行取模運算后得到的值很靠近趴拧,導致大量流量被調度給同一臺服務器,hash一致性算法會為每臺服務器計算多個hash兄渺,每個計算結果都放在圓環(huán)上作為虛擬服務器節(jié)點叔壤,數據位置不變嗅战,圓環(huán)上虛擬服務器節(jié)點增加,這樣數據就能在服務器間分布更均勻启具。

2、使用rewrite規(guī)則實現將所有到a域名的訪問rewrite到b域名

訪問www.magedu.org時薯演,永久重定向到www.mxx.com

[root@centos8mini ~]# cat /data/nginx/conf/conf.d/server4.conf
server{
    listen 80;
    server_name www.magedu.org;
    rewrite / http://www.mxx.com permanent;
}

[root@centos8mini ~]# cat /data/nginx/conf/conf.d/server1.conf
server {
    listen 80;
    server_name www.mxx.com;
     root /data/server1;
    access_log logs/www-access.log main;
    location / {
        index index.html;
        
    }
}

修改hsots文件:

192.168.32.53 www.mxx.com
192.168.32.53 www.magedu.org

訪問測試:

image.png

3、實現反向代理客戶端IP透傳

  • 配置后端服務器群組
[root@centos8mini ~]# cat /data/nginx/conf/nginx.conf
http {
    upstream webserver {
        server 192.168.32.53;
        server 192.168.32.54;
    }
...
  • 配置代理
[root@centos8mini ~]# cat /data/nginx/conf/conf.d/proxy.conf
server {
    listen 80;
    server_name s1.mxx.com;
    access_log logs/s1-access.log main;
    location / {
        proxy_pass http://webserver;  #指向群主
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;  #傳遞Client IP給后端服務器
        proxy_set_header Host www.mxx.com;  #修改HTTP請求頭的Host字段衡创,因為默認會被修改為webserver,導致無法訪問后端服務器配置的虛擬主機
    }
}
  • 后端服務器開啟access_log
[root@centos8mini src]# cat /data/nginx/conf/nginx.conf
...
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"'
                      '"$http_host"';
...

[root@centos8mini src]# cat /data/nginx/conf/conf.d/server1.conf
server {
    listen 80;
    server_name www.mxx.com;
    root /data/server1;
    access_log logs/www-access.log main;
    location / {
        index index.html;
        
    }
}
  • 訪問測試,倒數第二個字段就是x-forwarded-for塘秦,記錄了客戶端IP
image.png

4、利用LNMP實現wordpress站點搭建

使用ansible搭建php-fpm

  • ansible配置
[root@ansible ~]# tree ansible/
ansible/
├── ansible.cfg
├── inventory
├── mysql-install.yml
└── php-fpm.yml

0 directories, 4 files

[root@centos8-1 ansible]# cat ansible.cfg 
[defaults]
inventory = inventory
remote_user = root
host_key_checking = false
module_name = shell

[root@ansible ansible]# cat inventory
[localhost]
192.168.32.128

[mysql]
192.168.32.123

[websrv]
192.168.32.123

[php_fpm]
192.168.32.125

  • 安裝php-fpm
- hosts: php_fpm
  vars:
    - phpfpm_ip: 192.168.32.125
    - httpdfile: httpd-2.4.52
    - aprfile: apr-1.7.0
    - aprutilfile: apr-util-1.6.1
    - mysqlfile: mysql-5.7.35-linux-glibc2.12-x86_64.tar.gz
    - mysqlpath: mysql-5.7.35-linux-glibc2.12-x86_64
    - mysqlversion: MySQL-5.7
    - apppath: /usr/local
    - nginx_path: /data/httpd24
    - nginxfile: /data/httpd24/conf/httpd.conf
    - oniguruma_url: https://github.com/kkos/oniguruma/archive/v6.9.4.tar.gz
    - oniguruma: oniguruma-6.9.4
    - oniguruma_file: /usr/lib64/pkgconfig/oniguruma.pc
    - phpsource: php-7.4.27
    - phppath: /data/php74
    - php_file: "/data/php74/var/run/php-fpm.pid"
    - wp_url: https://cn.wordpress.org/latest-zh_CN.tar.gz
    - wp_name: latest-zh_CN.tar.gz
    - discuz_url: http://download.comsenz.com/DiscuzX/3.3/Discuz_X3.3_SC_UTF8.zip
    - discuz_name: Discuz_X3.3_SC_UTF8.zip
  vars_prompt: 
      name: lisenallowedclients
      prompt: "你希望通過哪臺主機連接php-fpm?(請輸入IP地址京痢,如:192.168.11.7)" 
      private: no
  tasks:
    - name: 文件下載
      block:
        - shell: setenforce 0
          ignore_errors: true
        - service: name=firewalld state=stopped enabled=no
        - replace: path=/etc/selinux/config regexp="^(SELINUX=).*" replace="\1disabled" backup=yes
        - name: 文件下載
          block:
            - shell: ls -1 /root/
              register: lsroot
              ignore_errors: yes
            - get_url: url="{{oniguruma_url}}" dest="/root/{{oniguruma}}.tar.gz"
              when: "(oniguruma + '.tar.gz') not in lsroot.stdout_lines"
            - get_url: url="https://www.php.net/distributions/{{phpsource}}.tar.xz" validate_certs=false dest=/root/
              when: "(phpsource + '.tar.xz') not in lsroot.stdout_lines"
        - name: oniguruma編譯安裝
          block:
            - unarchive: src=/root/{{oniguruma}}.tar.gz dest=/root/ copy=no
            - yum: name="gcc,openssl-devel,libxml2-devel,bzip2-devel,libmcrypt-devel,sqlite-devel,autoconf,automake,libtool" state=latest
            - wait_for: path=/root/{{oniguruma}}/autogen.sh state=present
            - shell: chdir=/root/{{oniguruma}} ./autogen.sh && ./configure --prefix=/usr
              register: onigurumaconfig
            - shell: chdir=/root/{{oniguruma}} make -j 2 && make install
              when: onigurumaconfig.rc == 0
          when: "oniguruma_file is not exists"
        - name: php-fpm編譯安裝
          block:
            - unarchive: src=/root/{{phpsource}}.tar.xz dest=/root/ copy=no
            - wait_for: path=/root/{{phpsource}} state=present
            - shell: chdir=/root/{{phpsource}} ./configure --prefix={{phppath}} --enable-mysqlnd --with-mysqli=mysqlnd --with-pdo-mysql=mysqlnd --with-openssl --with-zlib  --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d --enable-mbstring --with-gd --enable-xml --enable-sockets --enable-fpm --enable-maintainer-zts --disable-fileinfo
              register: phpconfig
            - shell: chdir=/root/{{phpsource}} make -j 2 && make install
              when: phpconfig.rc == 0
            - wait_for: path="{{phppath}}" state=present
            - name: 添加man幫助
              lineinfile: path=/etc/man_db.conf insertafter="^MANDATORY_MANPATH" line="MANDATORY_MANPATH           {{phppath}}/php/man"
            - block:
                - copy: src={{phppath}}/{{item.k}} dest={{phppath}}/{{item.v}} remote_src=yes
                  loop:
                    - {k: etc/php-fpm.conf.default, v: etc/php-fpm.conf}
                    - {k: etc/php-fpm.d/www.conf.default, v: etc/php-fpm.d/www.conf}
                - name: 修改php-fpm.conf文件
                  lineinfile: path={{phppath}}/etc/php-fpm.conf regexp="{{item.k}}" line="{{item.v}}" backrefs=true
                  loop:
                    - {k: ^;pid(.*)$, v: pid\1 }
                    - {k: ^;error_log(.*)$, v: error_log\1}
                - name: 修改www.conf文件
                  lineinfile: path={{phppath}}/etc/php-fpm.d/www.conf regexp="{{item.k}}" line="{{item.v}}" backrefs=true
                  loop:
                    - {k: ^user = nobody, v: user = nginx}
                    - {k: ^group = nobody, v: group = nginx}
                    - {k: ^listen.*, v: listen = 9000}
                    - {k: ^;listen\.allowed_clients.*, v: "listen.allowed_clients = {{lisenallowedclients}}"}
                    - {k: ^;pm.status_path(.*), v: pm.status_path\1}
                    - {k: ^;ping.path(.*), v: ping.path\1}
                    - {k: ^;ping.response(.*), v: ping.response\1}
                    - {k: ^;access.log(.*), v: access.log = /data/php74/var/log/access.log}
                    - {k: ^;access.format(.*), v: access.format\1}
                    - {k: "php_value[session.save_handler].*", v: "php_value[session.save_handler] = files"}
                - name: no matching line has to use "insertafter" option
                  lineinfile: path={{phppath}}/etc/php-fpm.d/www.conf insertafter="{{item.k}}" line="{{item.v}}"
                  loop:
                    - {k: "php_value[session.save_path].*", v: "php_value[session.save_path] = /data/php74/log/session"}
              tags: phpconfigfile
          when: "php_file is not exists"
        - block:
            - copy:
                content: |
                    # It's not recommended to modify this file in-place, because it
                    # will be overwritten during upgrades.  If you want to customize,
                    # the best way is to use the "systemctl edit" command
                    [Unit]                    
                    Description=The PHP FastCGI Process Manager
                    After=syslog.target network.target
                    [Service]                 
                    Type=forking
                    ExecStart=/data/php74/sbin/php-fpm --daemonize
                    ExecReload=/bin/kill -USR2 $MAINPID
                    PrivateTmp=tru
                    [Install]
                    WantedBy=multi-user.target
                dest: /usr/lib/systemd/system/php74-php-fpm.service
                mode: u+x
            - shell: systemctl daemon-reload
            - block:
                - shell: id nginx
                  register: nginxid
                  ignore_errors: true
                - block:
                    - group: name=nginx system=yes state=present
                    - user: name=nginx system=yes group=nginx state=present shell=/sbin/nologin
                  when: nginxid.rc != 0
              tags: nginx_user
            - service: name=php74-php-fpm.service state=restarted enabled=yes
          tags: phpservicefile
      when: "'php_fpm' in group_names"
      tags: phpfpminstall

ansible安裝mysql5.7

---
- hosts: mysql
  vars:
    - mysqlfile: mysql-5.7.35-linux-glibc2.12-x86_64.tar.gz
    - mysqlpath: mysql-5.7.35-linux-glibc2.12-x86_64
    - mysqlversion: MySQL-5.7
    - apppath: /usr/local
  tasks:
    - service:
        name: firewalld
        state: stopped
        enabled: no
    - shell: sed -r -i.bak 's/(^SELINUX=).*/\1permissive/g' /etc/selinux/config
    - shell: setenforce 0
    - yum: name="libaio,numactl-libs" state=present
    - shell: id mysql
      register: mysqlid
      ignore_errors: true
    - block:
        - group: name=mysql gid=306 system=yes state=present
        - user: name=mysql system=yes uid=306 group=mysql state=present home=/data/mysql shell=/bin/false
      when: mysqlid.rc != 0
    - shell: ls -1 /root/{{ mysqlfile }}
      register: mysqllsinfo
      ignore_errors: true
    - get_url: url="http://mirrors.163.com/mysql/Downloads/{{mysqlversion}}/{{mysqlfile}}" dest=/root/
      when: mysqllsinfo.rc != 0
    - file: dest=/data/mysql state=directory owner=mysql group=mysql
    - shell: ls -1 {{apppath}}/{{mysqlpath}}
      register: checkmysqlpath
      ignore_errors: true
    - unarchive: src=/root/{{ mysqlfile }} dest={{apppath}} copy=no
      when: checkmysqlpath.rc != 0
    - file: dest={{ apppath }}/mysql src={{ apppath }}/{{ mysqlpath }} state=link
    - file: dest={{apppath}}/mysql/ state=directory owner=root group=root recurse=yes
    - file: dest="{{ item.name }}" state="{{ item.state }}" owner=mysql group=mysql
      loop:
        - { name: '/etc/my.cnf', state: 'touch' }
        - { name: '/etc/my.cnf.d', state: 'directory' }
        - { name: '/var/log/mysql', state: 'directory' }
    - copy:
        content: |
            [mysqld]
            datadir = /data/mysql
            innodb_file_per_table = on
            skip_name_resolve = on 
            log_warnings=2
            log_error=/var/log/mysql/mysql.log
            general_log=on
            general_log_file=/var/log/mysql/mysql-gen.log
            log_output=file


            [client]

            !includedir /etc/my.cnf.d
        dest: /etc/my.cnf
    - shell: ls -1a /data/mysql
      register: checkdatadirectory
    - shell: rm -rf /data/mysql/*
      when: checkdatadirectory["stdout_lines"] | length > 2
    - shell: "{{apppath}}/mysql/bin/mysqld --initialize-insecure --user=mysql --datadir=/data/mysql"
      register: initsql
    - debug:
        msg: "mysql database initialize Successed!"
      when: initsql.rc == 0
    - shell: echo 'PATH=/usr/local/mysql/bin:$PATH' > /etc/profile.d/mysql.sh
    - name: activate PATH_varia 
      shell: source /etc/profile.d/mysql.sh
    - shell: echo $PATH
      register: pathvari
    - debug:
        msg: "{{ pathvari.stdout }}"
    - copy: src={{apppath}}/mysql/support-files/mysql.server dest=/etc/init.d/mysqld remote_src=yes mode=u+x
    - shell: chkconfig --add mysqld
    - shell: chkconfig mysqld on
    - shell: service mysqld start
    - name: 創(chuàng)建遠程賬戶和數據庫
      block:
        - shell: mysql -e "create user if not exists root@'%' identified by 'root';grant all on *.* to root@'%';"
        - shell: mysql -e "create database if not exists wordpress;"
      tags: C_user

安裝nginx

#!/bin/bash
#****************************************************************************************#
#Author:                        Yabao11
#QQ:                            what QQ邑蒋,no QQ
#Date:                          2022-01-04
#FileName:                      nginx.sh
#URL:                           https://github.com/yabao11
#Description:                   Test Script
#Copyright (C):                 2022 All rights reserved
#*******************************定義顏色*************************************************#
RED="\e[1;31m"
GREEN="\e[1;32m"
SKYBLUE="\e[1;36m"
YELLOW="\e[1;43m"
BLUE="\e[1;44m"
END="\e[0m"
RandomColor="\e[1;32m"
#****************************************************************************************#
function Ostype {
    if grep -i -q "release 6" /etc/centos-release;then
      echo Centos6
    elif grep -i -q Centos-8 /etc/os-release;then
      echo Centos
    elif grep -i -q Centos-7 /etc/os-release;then
      echo Centos7
    elif grep -i -q Ubuntu /etc/os-release;then
      echo Ubuntu
    elif grep -i -q "RedHat" /etc/os-release;then
      echo Redhat
    fi
}

function color {
  RES_COL=60
  MOVE_TO_COL="echo -en \E[${RES_COL}G"
  SETCOLOR_SUCCESS="echo -en \E[1;32m"
  SETCOLOR_FAILURE="echo -en \E[1;31m"
  SETCOLOR_WARNING="echo -en \E[1;33m"
  SETCOLOR_NORMAL="echo -en \E[0m"
  echo -n "$1" && $MOVE_TO_COL
  echo -n "["
  if [[ $2 = "success" || $2 = "0" ]]; then
    ${SETCOLOR_SUCCESS}
    echo -n "  OK  "
  elif [[ $2 = "failure" || $2 = "1" ]]; then
    ${SETCOLOR_FAILURE}
    echo -n "FAILED"
  else
    ${SETCOLOR_WARNING}
    echo -n "WARNING"
  fi
  ${SETCOLOR_NORMAL}
  echo -n "]"
  echo
}

function inputerror {
    echo -en "輸入錯誤!"
    echo -e "\E[${RES_COL}G["$RED"退出"$END"]"
}


function nginx_install {
    echo -e $GREEN"開始安裝編譯軟件.."$END
    yum -y install wget gcc pcre-devel openssl-devel zlib-devel > /dev/null || { color "軟件安裝失敗.." 1; return 1; }
    echo -e $GREEN"開始下載源碼包.."$END
    [ -e ${file_path}/${nginx_file}.tar.gz ] || wget -P ${file_path}/ http://nginx.org/download/${nginx_file}.tar.gz > /dev/null || { color "文件下載失敗.." 1; return 1; }
    echo -e $GREEN"執(zhí)行解壓縮.."$END
    tar xf ${file_path}/${nginx_file}.tar.gz -C ${file_path}/ > /dev/null || { color "文件解壓縮失敗.." 1; return 1; }
    useradd -r -M -s /sbin/nologin nginx
    cd ${file_path}/${nginx_file} || { color "找不到目錄.." 1;return 1; }
    if [ $# -gt 4 ];then
        echo -e $GREEN"執(zhí)行./configure.."$END
        ./configure $* > /dev/null && color "configure成功.." 0 || { color "configure失敗.." 1; return 1; }
        echo -e $GREEN"執(zhí)行make.."$END
        make -j `lscpu | awk 'NR==4{print $2}'` > /dev/null && color "make成功!" 0 || { color "make失敗.." 1; return 1; }

#如果直接在腳本后面提供了nginx版本,則安裝該版本的nginx草描,可使用默認參數饿敲,或用戶自己指定參數
    else
        [ ]
        if [ -e ${nginx_path} ]; then
            read -p "/data/nginx 文件已存在,是否強制安裝(會直接刪除/data/nginx)瓢对?(yes or no)" askuser
            askuser=`echo $askuser | tr 'A-Z' 'a-z'`
            case $askuser in
            y|yes)
                rm -rf /data/nginx
            ;;
            n|no)
                exit
            ;;
            *)
                inputerror
                exit
            ;;
            esac
        else
            echo -e $GREEN"開始執(zhí)行configure.."$END
        fi
        read -p "你是否想要使用腳本默認的參數安裝硕并?(回車使用默認參數倔毙,或輸入自己的參數)" readpref
        [ -v readpref ] && echo -e "警告!你自行輸入了編譯參數毙玻,路徑參數除了--prefix=之外,不要定義其他路徑參數运准!給你2秒確認一下缭受。"$END; sleep 2;
        if [[ $readpref =~ path ]];then 
        read -p "還有path參數在里面...真的不能帶path胁澳,你確定要繼續(xù)?" readaction
        readaction=`echo $readaction | tr 'A-Z' 'a-z'`
        case $readaction in
            y|yes)
            ;;
            n|no)
                exit
            ;;
            *)
                inputerror
                exit
            ;;
        esac
        fi
        default_statement=(${readpref:="--prefix=${nginx_path} --user=nginx --group=nginx --with-http_ssl_module --with-http_v2_module --with-http_realip_module --with-http_stub_status_module --with-http_gzip_static_module --with-pcre --with-stream --with-stream_ssl_module --with-stream_realip_module"})
        [ ${#default_statement[*]} -gt 4 ] && echo -e $GREEN"開始執(zhí)行configure.."$END || exit;
        [ -v readpref ] && nginx_path=${default_statement[0]#*=}
            echo -e $GREEN"執(zhí)行./configure.."$END
            ./configure ${default_statement[*]} > /dev/null && color "configure成功.." 0 || { color "configure失敗.." 1; exit; }
            echo -e $GREEN"執(zhí)行make.."$END
            make -j `lscpu | awk 'NR==4{print $2}'` > /dev/null && color "make成功!" 0 || { color "make失敗.." 1; exit; }
            echo -e $GREEN"執(zhí)行make install米者,開始安裝了韭畸!"$END
            make install > /dev/null && color "install成功!" 0 || { color "install失敗.." 1; exit; }
            mkdir -p ${nginx_path}/run
            mkdir ${nginx_path}/conf/conf.d
            chown -R nginx.nginx ${nginx_path}
            echo -e $GREEN"創(chuàng)建軟鏈接.."$END
            [ -e /usr/sbin/nginx ] && { color "nginx軟鏈接存在,需刪除" 2; rm -rf /usr/sbin/nginx; }
            ln -s ${nginx_path}/sbin/nginx /usr/sbin/ &> /dev/null || color "/usr/sbin/nginx創(chuàng)建失敗蔓搞,請自行創(chuàng)建鏈接.." 1
            cat > /usr/lib/systemd/system/nginx.service <<EOF
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=${nginx_path}/run/nginx.pid
ExecStart=/usr/sbin/nginx -c ${nginx_path}/conf/nginx.conf
ExecReload=/bin/sh -c "/bin/kill -s HUP \$(/bin/cat ${nginx_path}/run/nginx.pid)"
ExecStop=/bin/sh -c "/bin/kill -s TERM \$(/bin/cat ${nginx_path}/run/nginx.pid)"
LimitNOFILE=100000

[Install]
WantedBy=multi-user.target
EOF
            chown nginx.nginx /usr/lib/systemd/system/nginx.service
            color "服務配置完畢胰丁,請自行啟動甘萧!" 2
            tar -P -zcf ${file_path}/${nginx_file}/man/nginx.8.gz ${file_path}/${nginx_file}/man/nginx.8
            mv ${file_path}/${nginx_file}/man/nginx.8.gz /usr/share/man/man8/
            color "man幫助配置完畢邀泉!" 0
            nginx_config
            systemctl daemon-reload
    fi
}

function nginx_config {
    [ -e ${nginx_path}/conf/nginx.conf ] || { color "文件沒找到.." 1; exit; }
    echo -e $GREEN"修改配置文件.."$END
    sed -i.bak -r -e "s/#user.*/user nginx nginx;/" \
                  -e "s/worker_processes.*/worker_processes  auto;/" \
                  -e "/#error\_log\ \ logs\/error\.log;/i\error_log  logs/error.log warn;\npid        ${nginx_path}/run/nginx.pid;\nworker_rlimit_nofile 65536;" \
                  -e "/[[:space:]]+worker\_connections.*/i\use epoll;\naccept_mutex  on;\nmulti_accept  on;\n" \
                  -e "s/[[:space:]]+worker_connections.*/worker_connections  65536;/" \
                  -e "s/[[:space:]]+keepalive_timeout.*/keepalive_timeout  65 65;/" \
                  -e "/[[:space:]]+# HTTPS server/i\keepalive_requests 3;\ninclude ${nginx_path}/conf/conf.d/*.conf;\n" ${nginx_path}/conf/nginx.conf && { color "配置文件修改成功财岔!" 0; echo -e $GREEN"你可以將服務器配置放在${nginx_path}/conf/conf.d/*.conf中魔眨。"$GREEN; }
}


function RootCA {
    CAsubject="/C=CN/ST=Shanghai/O=MXX Company Ltd,/CN=MxxRootCA"
    local con
    if ! [ -d /etc/pki/CA ];then
        echo -e $GREEN"CA目錄不存在,開始創(chuàng)建CA目錄..."$END
        mkdir -pv ${cafile_path}{certs,crl,newcerts,private}
        touch ${cafile_path}index.txt
        echo -n 01 > ${cafile_path}serial
        echo -n 01 > ${cafile_path}crlnumber
        openssl req -newkey rsa:2048 -subj "$CAsubject" -keyout ${cafile_path}private/cakey.pem -nodes -days 3650 -x509 -out ${cafile_path}cacert.pem
    else
        ! [ -e ${cafile_path}index.txt ] && { touch ${cafile_path}index.txt;echo -e $GREEN"index.txt創(chuàng)建成功盖灸!"$END;}
        ! [ -e ${cafile_path}serial ] && { echo -n 01 > ${cafile_path}serial;echo -e $GREEN"serial創(chuàng)建成功!"$END;}
        ! [ -e ${cafile_path}crlnumber ] && { echo -n 01 > ${cafile_path}crlnumber;echo -e $GREEN"crlnumber創(chuàng)建成功间螟!"$END;}
            if ! [ -e ${cafile_path}private/cakey.pem -o -e ${cafile_path}cacert.pem ];then
                echo -e $GREEN"生成cakey.pem|cacert.pem文件..."$END
                openssl req -utf8 -newkey rsa:2048 -subj "$CAsubject" -keyout ${cafile_path}private/cakey.key -nodes -days 3650 -x509 -out ${cafile_path}cacert.crt
            fi
    fi
    if [ $? -eq 0 ];then
        color "設備配置為RootCA成功笆焰!" 0
    else
        color "RootCA配置失斘撮荨香追!" 1
        return
    fi
}

function certgen {
    read -p "你想自己設置證書參數么?(yes or no)" certset
    certset=`echo $certset | tr 'A-Z' 'a-z'`
    case $certset in
    y|yes)
        while ((num<2));do
            read -p "輸入你希望為哪個站點申請證書漩氨?(如:*.mxx.com):" sub
            manualSubject="/C=CN/ST=Shanghai/O=MXX Company Ltd,/CN="${sub}
            read -p "輸入你證書的名稱:" pkiname
            openssl req -newkey rsa:2048 -subj "$manualSubject" -keyout ${cafile_path}private/${pkiname}.key -nodes -out ${cafile_path}${pkiname}.csr &> /dev/null && color "csr生成成功缓待!" 0 || { color "csr生成失敗.." 1;exit; }
            #生成的證書前面帶了一堆狀態(tài)信息
            #openssl ca -days 3650 -in ${cafile_path}${pkiname}.csr -cert ${cafile_path}cacert.pem -keyfile ${cafile_path}private/cakey.pem     -out ${cafile_path}certs/${pkiname}.crt -batch &> /dev/null && color "證書生成成功!" 0 || { color "證書生成失敗.." 1;exit; }
            openssl x509 -req -in ${cafile_path}${pkiname}.csr -CA ${cafile_path}cacert.pem -CAkey ${cafile_path}private/cakey.pem  -CAcreateserial -days 3650 -CAserial ${cafile_path}serial -out ${cafile_path}certs/${pkiname}.crt &> /dev/null && color "證書生成成功敲长!" 0 || { color "證書生成失敗.." 1;exit; }
            echo -e $GREEN"*************;*************************生成證書信息**************************************"$END
            cat ${cafile_path}certs/${pkiname}.crt | openssl x509 -noout -subject -dates -serial
            chmod 600 ${cafile_path}private/*.key
            echo  "證書生成完成"
            echo -e $GREEN"**************************************生成證書文件如下**************************************"$END
            echo "證書存放目錄: "${cafile_path}certs/
            echo "證書文件列表: "`ls -t1 ${cafile_path}certs/${pkiname}*`
            while true;do
                read -p "是否希望合并根證書和服務器證書月褥?" askuser2
                askuser2=`echo $askuser2 | tr 'A-Z' 'a-z'`
                case $askuser2 in
                y|yes)
                    cat ${cafile_path}certs/${pkiname}.crt ${cafile_path}cacert.pem > /root/${pkiname}_merge.pem && color "合并后的證書的存放位置在/root/"${pkiname}"_merge.pem" 0 || color "證書合并失敗.." 1
                    break
                ;;
                n|no)
                    break
                ;;
                *)
                    inputerror
                    continue
                ;;
                esac
            done
            while true;do
                read -p "是否需要繼續(xù)生成證書挚躯?" askuser3
                askuser3=`echo $askuser3 | tr 'A-Z' 'a-z'`
                case $askuser3 in
                y|yes)
                    num=1
                    break
                ;;
                n|no)
                    break 3
                ;;
                *)
                    inputerror
                    break
                ;;
                esac
            done
        done
    ;;
    n|no)
        local INPUT
        read -p "生成多少個證書堂鲤?" INPUT
        for((i=1;i<=$INPUT;i++));do
            local Rand=`openssl rand -base64 6|sed -rn 's/[/+]//g;p'`
            [ $INPUT -eq 2 ] && DN=([1]=Master [2]=Slave) || DN[$i]="centos-$i"
            ClientSubject="/C=CN/ST=Shanghai/O=MXX Company Ltd,/OU=$Rand/CN=${DN[$i]}.mxx.com"
            openssl req -newkey rsa:2048 -subj "$ClientSubject" -keyout ${cafile_path}private/user-${Rand}.key -nodes -out ${cafile_path}user-${Rand}.csr &> /dev/null
            #openssl ca -days 3650 -in ${cafile_path}user-${Rand}.csr -cert ${cafile_path}cacert.pem -keyfile ${cafile_path}private/cakey.pem -out ${cafile_path}certs/user-${Rand}.crt -batch &> /dev/null
            #下面的命令雖然可以生成證書,但不會寫index文件
            openssl x509 -req -in ${cafile_path}user-${Rand}.csr -CA ${cafile_path}cacert.pem -CAkey ${cafile_path}private/cakey.pem -CAcreateserial -days 3650 -CAserial ${cafile_path}serial -out ${cafile_path}certs/user-${Rand}.crt
            echo -e $GREEN"*************;*************************生成證書信息**************************************"$END
            cat ${cafile_path}certs/user-${Rand}.crt | openssl x509 -noout -subject -dates -serial
        done
        chmod 600 ${cafile_path}private/*.key
        echo  "證書生成完成"
        echo -e $GREEN"**************************************生成證書文件如下**************************************"$END
        echo "證書存放目錄: "${cafile_path}certs/
        echo "證書文件列表: "`ls -t1 ${cafile_path}certs/ | head -n $INPUT`
    ;;
    *)
        inputerror
    ;;
    esac
}

function csrgen {
  local cafile_path=/etc/pki/CA/
  local capath
  local days
  read -p "CSR文件的文件路徑和文件名(如:/root/xxx.csr)?" capath
  read -p "CSR文件的有效期?" days
  local crtfile=`echo "$capath" | sed -r -n 's/(.*)\.csr/\1/p'`
    openssl ca -days $days -in $capath -cert ${cafile_path}cacert.pem -keyfile ${cafile_path}private/cakey.pem -out ${crtfile}.crt -batch &> /dev/null
    echo -e $GREEN"**************************************生成證書信息**************************************"$END
    cat ${crtfile}.crt | openssl x509 -noout -subject -dates -serial
  echo  "證書生成完成"
  echo -e $GREEN"**************************************生成證書文件如下**************************************"$END
  echo "證書存放目錄: "${crtfile}
}

function config_https {
        local nginx_conf=`find / -type d -name conf.d | grep nginx`
        read -p "輸入網站的名字:" website
        read -p "輸入你證書的文件名(應該是xxx_merge):" pkiname2
        [ -e "/root/${pkiname2}.pem" ] || { color "證書不存在.." 1;exit; }
        [ -e ${nginx_conf}/server${i}.conf ] && ((i++));
        cat > ${nginx_conf}/server${i}.conf <<EOF && color "配置文件生成成功" 0 || { color "配置文件生成失敗.." 1; exit; }
server {
    listen 80;
    listen 443 ssl;
    server_name ${website};
    ssl_certificate /root/${pkiname2}.pem;
    ssl_certificate_key /etc/pki/CA/private/${pkiname2%_*}.key;
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    root /data/server${i};
    location / {
        index index.html;
        if ( \$scheme = http ) {
            rewrite ^/(.*)$ https://${website}/\$1 redirect;
        }
    }
}
EOF
        mkdir /data/server${i}
        cat > /data/server${i}/index.html <<EOF
<h1>This is my server${i}, website doamin name is ${website}!</h1>
EOF
[ $? -eq 0 ] && color "配置成功悠就!" 0 || color "配置失敗.." 1
}

function wordpress_install {
    i=1
    local nginx_conf=`find / -type d -name conf.d | grep nginx`
    read -p "輸入fastcgi服務器的地址" fastip
    echo -e $GREEN"文件下載中.."$END
    yum -y install wget > /dev/null
    ls /root/latest-zh_CN.tar.gz && echo -e $GREEN"文件已存在"$END || wget https://cn.wordpress.org/latest-zh_CN.tar.gz -P /root/ > /dev/null
    { mv wordpress* latest-zh_CN.tar.gz; ls latest-zh_CN.tar.gz; } || { color "文件不存在.." 1; exit; }
    tar xf /root/latest-zh_CN.tar.gz
    [ -e /data/server${i} ] && ((i++))
    mkdir /data/server${i} || color "目錄/data/server${i}已存在,將直接使用該目錄" 2
    cp -a /root/wordpress /data/server${i}/
    cat > ${nginx_conf}/server${i}.conf <<EOF && color "配置文件生成成功" 0 || { color "配置文件生成失敗.." 1; exit; }
server {
    listen 80;
    server_name blog.mxx.com;
    location / {
        index index.php;
        root /data/server/wordpress;
        }
    location ~ \.php$|status|ping {
        root /data/server/wordpress;
        fastcgi_pass ${fastip}:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}
EOF
    echo -e $RED"如果php-fpm和nginx不在同一臺滞诺,需要將wordpress復制到php-fpm的/data/server${i}目錄下望门,修改好權限,然后再執(zhí)行安裝"$END
}

#變量
nginx_file=${1:-nginx-1.18.0}
nginx_path=/data/nginx
file_path=/usr/local/src
cafile_path=/etc/pki/CA/

if [ $# -eq 1 ];then
    if [ "$1" == --help ];then
        echo -e $GREEN"命令格式:"$END
        echo -e $SKYBLUE"./"`basename ./$0`" --help:查看幫助"$END
        echo -e $SKYBLUE"./`basename ./$0` NGINX_VERSION:編譯安裝對應版本的nginx(使用默認編譯選項)"$END
        echo -e $SKYBLUE"./`basename ./$0`:查看菜單項"$END
    else
        nginx_install ${nginx_file} || { color "安裝失敗门烂,參數錯誤崩溪!" 1;exit; }
    fi
else
    j=1
    PS3="請選擇您要執(zhí)行的操作F柯瘛:"
    MENU="
    默認選項安裝nginx
    nginx補充新模塊(僅編譯剩膘,不安裝)慈格,用于添加新模塊
    配置nginx
    配置RootCA餐茵,生成自簽名證書
    生成服務器證書
    配置HTTPS服務
    配置wordpress
    查看命令幫助
    退出
    "

    select M in $MENU ;do
        case $REPLY in
            1)
                nginx_install
            ;;
            2)
            read -p "你是否想要自行提供編譯參數(至少4個)?(直接回車使用我給你定義的參數)" askpref
    install_statement=${askpref:="--prefix=/etc/nginx \
--sbin-path=/usr/sbin/nginx \
--modules-path=/usr/lib64/nginx/modules \
--conf-path=/etc/nginx/nginx.conf \
--error-log-path=/data/nginx/log/nginx/error.log \
--http-log-path=/data/nginx/log/nginx/access.log \
--pid-path=/data/nginx/run/nginx.pid \
--lock-path=/data/nginx/run/nginx.lock \
--http-client-body-temp-path=/data/nginx/cache/nginx/client_temp \
--http-proxy-temp-path=/data/nginx/cache/nginx/proxy_temp \
--http-fastcgi-temp-path=/data/nginx/cache/nginx/fastcgi_temp \
--http-uwsgi-temp-path=/data/nginx/cache/nginx/uwsgi_temp \
--http-scgi-temp-path=/data/nginx/cache/nginx/scgi_temp \
--user=nginx \
--group=nginx \
--with-compat \
--with-file-aio \
--with-threads \
--with-http_addition_module \
--with-http_auth_request_module \
--with-http_dav_module \
--with-http_flv_module \
--with-http_gunzip_module \
--with-http_gzip_static_module \
--with-http_mp4_module \
--with-http_random_index_module \
--with-http_realip_module \
--with-http_secure_link_module \
--with-http_slice_module \
--with-http_ssl_module \
--with-http_stub_status_module \
--with-http_sub_module \
--with-http_v2_module \
--with-mail \
--with-mail_ssl_module \
--with-stream \
--with-stream_realip_module \
--with-stream_ssl_module \
--with-stream_ssl_preread_module"}
                nginx_install ${install_statement}
            ;;
            3)
                nginx_config
            ;;
            4)
                [ -e /etc/pki/CA ] && rm -rf /etc/pki/CA
                RootCA
            ;;
            5)
                read -p "您是否有csr文件?(yes or no)" csrfileyes
                csrfileyes=`echo $csrfileyes | tr 'A-Z' 'a-z'`
                case $csrfileyes in
                y|yes)
                    csrgen
                    ;;
                n|no)
                    certgen
                    ;;
                *)
                    inputerror
                    ;;
                esac
            ;;
            6)
                i=1
                while true;do
                    config_https
                read -p "是否需要繼續(xù)生成下一個網站?" askuser4
                askuser4=`echo $askuser4 | tr 'A-Z' 'a-z'`
                case $askuser4 in
                y|yes)
                    ((i++))
                    continue
                    ;;
                n|no)
                    break 2
                    ;;
                *)
                    inputerror
                    break 2
                    ;;
                esac
                done
            ;;
            7)
                wordpress_install
            ;;
            8)
                echo -e $GREEN"命令格式:"$END
                echo -e $SKYBLUE"./"`basename ./$0`" --help:查看幫助"$END
                echo -e $SKYBLUE"./`basename ./$0` NGINX_VERSION:編譯安裝對應版本的nginx(使用默認編譯選項)"$END
                echo -e $SKYBLUE"./`basename ./$0`:查看菜單項"$END
            ;;
            *)
            exit
            ;;
        esac
        done
fi


#--prefix=/data/nginx --user=nginx --group=nginx --with-compat --with-file-aio --with-threads --with-http_addition_module --with-http_auth_request_module --with-http_dav_module --with-http_flv_module --with-http_gunzip_module --with-http_gzip_static_module --with-http_mp4_module --with-http_random_index_module --with-http_realip_module --with-http_secure_link_module --with-http_slice_module --with-http_ssl_module --with-http_stub_status_module --with-http_sub_module --with-http_v2_module --with-mail --with-mail_ssl_module --with-stream --with-stream_realip_module --with-stream_ssl_module --with-stream_ssl_preread_module --add-module=/usr/local/src/echo-nginx-module


#git clone https://github.com/openresty/echo-nginx-module.git
  • 啟動nginx服務
systemctl restart nginx

補充部分配置

#在125主機上創(chuàng)建目錄
mkdir /data/serverX  #X默認是1,除非之前也創(chuàng)建過/data/server1糊啡,會變成2
chown nginx.nginx /data/serverX

#在123主機上復制
scp -r /root/wordpress 192.168.32.125:/data/serverX/

windows hosts文件里添加192.168.32.123 指向域名blog.mxx.com

訪問http://blog.mxx.com進入安裝界面安裝wordpress

測試結果

image.png
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末稍算,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子役拴,更是在濱河造成了極大的恐慌糊探,老刑警劉巖,帶你破解...
    沈念sama閱讀 210,978評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件河闰,死亡現場離奇詭異科平,居然都是意外死亡,警方通過查閱死者的電腦和手機姜性,發(fā)現死者居然都...
    沈念sama閱讀 89,954評論 2 384
  • 文/潘曉璐 我一進店門瞪慧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人污抬,你說我怎么就攤上這事汞贸。” “怎么了印机?”我有些...
    開封第一講書人閱讀 156,623評論 0 345
  • 文/不壞的土叔 我叫張陵矢腻,是天一觀的道長。 經常有香客問我射赛,道長多柑,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,324評論 1 282
  • 正文 為了忘掉前任楣责,我火速辦了婚禮竣灌,結果婚禮上,老公的妹妹穿的比我還像新娘秆麸。我一直安慰自己初嘹,他們只是感情好,可當我...
    茶點故事閱讀 65,390評論 5 384
  • 文/花漫 我一把揭開白布沮趣。 她就那樣靜靜地躺著屯烦,像睡著了一般。 火紅的嫁衣襯著肌膚如雪房铭。 梳的紋絲不亂的頭發(fā)上驻龟,一...
    開封第一講書人閱讀 49,741評論 1 289
  • 那天,我揣著相機與錄音缸匪,去河邊找鬼翁狐。 笑死,一個胖子當著我的面吹牛凌蔬,可吹牛的內容都是我干的露懒。 我是一名探鬼主播闯冷,決...
    沈念sama閱讀 38,892評論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼隐锭!你這毒婦竟也來了窃躲?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 37,655評論 0 266
  • 序言:老撾萬榮一對情侶失蹤钦睡,失蹤者是張志新(化名)和其女友劉穎蒂窒,沒想到半個月后,有當地人在樹林里發(fā)現了一具尸體荞怒,經...
    沈念sama閱讀 44,104評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡洒琢,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,451評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現自己被綠了褐桌。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片衰抑。...
    茶點故事閱讀 38,569評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖荧嵌,靈堂內的尸體忽然破棺而出呛踊,到底是詐尸還是另有隱情,我是刑警寧澤啦撮,帶...
    沈念sama閱讀 34,254評論 4 328
  • 正文 年R本政府宣布谭网,位于F島的核電站,受9級特大地震影響赃春,放射性物質發(fā)生泄漏愉择。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,834評論 3 312
  • 文/蒙蒙 一织中、第九天 我趴在偏房一處隱蔽的房頂上張望锥涕。 院中可真熱鬧,春花似錦狭吼、人聲如沸层坠。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,725評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽破花。三九已至,卻和暖如春采盒,著一層夾襖步出監(jiān)牢的瞬間旧乞,已是汗流浹背蔚润。 一陣腳步聲響...
    開封第一講書人閱讀 31,950評論 1 264
  • 我被黑心中介騙來泰國打工磅氨, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人嫡纠。 一個月前我還...
    沈念sama閱讀 46,260評論 2 360
  • 正文 我出身青樓烦租,卻偏偏與公主長得像延赌,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子叉橱,可洞房花燭夜當晚...
    茶點故事閱讀 43,446評論 2 348

推薦閱讀更多精彩內容