1、nginx负载均衡中常见的算法及原理有哪些?
RR:轮询
WRR:加权轮询
-
least_time header | last_byte [inflight];
考量服务器权重的前提下,将新的请求调度给最低平均响应时间和最少活动连接数的后端服务器;有多台都符合时就执行wrr;
如果指定了header,则response header的响应时间用来评估(
$upstream_header_time
);如果指定了last_byte,则完整的response的响应时间用来评估($upstream_response_time
);如果指定了inflight,则未完成的请求也作为评估条件
-
radom [two [method]]
考量服务器权重的前提下,将新请求按照随机方式调度给后端服务器组;
如果指定了two参数,则每次随机算法选中两台服务器,然后根据method指定的算法在这两台服务器中选中一台,默认的method是least_conn
-
least_conn;
- 考量服务器权重的前提下,将新的请求调度给由最少连接数量的后端服务器;如果这样的服务器有多台,就执行wrr方式调度;
-
ip_hash
- 新请求按照客户端的IP地址来调度,IPv4前三个8位组,或者整个IPv6地址将作为hash key,确保请求来自相同客户端将总是被调度给相同的服务器,除非这台服务器失效。
-
hash KEY
基于定义的KEY值执行HASH运算得到HASH值,key可以是文本,变量或者两者的结合,用这个值取模总权重,根据结果,归类到某一台后端服务器上
如果服务器出现增加或者删除时,将导致总权重值发生变化,原来调度给A服务器的会话都可能分散到其他服务器,导致之前的缓存失效
-
hash KEY consistent
执行ketama一致性hash算法,而不是仅通过hash值去判断服务器;
一致性hash算法将整个hash空间组织成一个虚拟的圆环,假设hash函数H的值空间是0到(232)-1,整个空间按顺时针方向组织,0和232-1在零点钟方向重合。
将服务器的信息,比如IP或主机名作为KEY,与H执行取模运算,得到的值一定会落在这个圆环的某一点上,这样每台服务器就确定了在HASH圆环上的位置。
将用户的请求也通过相同的方式,与H执行取模运算,同样得到一个落在圆环上的值,这个圆环上的值在圆环上顺时针运动,遇到的第一台服务器就是请求被调度到的服务器;
如果服务器过少时,可能导致服务器执行取模运算后得到的值很靠近,导致大量流量被调度给同一台服务器,hash一致性算法会为每台服务器计算多个hash,每个计算结果都放在圆环上作为虚拟服务器节点,数据位置不变,圆环上虚拟服务器节点增加,这样数据就能在服务器间分布更均匀。
2、使用rewrite规则实现将所有到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
访问测试:
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
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: 创建远程账户和数据库
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"执行解压缩.."$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"执行./configure.."$END
./configure $* > /dev/null && color "configure成功.." 0 || { color "configure失败.." 1; return 1; }
echo -e $GREEN"执行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"开始执行configure.."$END
fi
read -p "你是否想要使用脚本默认的参数安装?(回车使用默认参数,或输入自己的参数)" readpref
[ -v readpref ] && echo -e "警告!你自行输入了编译参数,路径参数除了--prefix=之外,不要定义其他路径参数!给你2秒确认一下。"$END; sleep 2;
if [[ $readpref =~ path ]];then
read -p "还有path参数在里面...真的不能带path,你确定要继续?" 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"开始执行configure.."$END || exit;
[ -v readpref ] && nginx_path=${default_statement[0]#*=}
echo -e $GREEN"执行./configure.."$END
./configure ${default_statement[*]} > /dev/null && color "configure成功.." 0 || { color "configure失败.." 1; exit; }
echo -e $GREEN"执行make.."$END
make -j `lscpu | awk 'NR==4{print $2}'` > /dev/null && color "make成功!" 0 || { color "make失败.." 1; exit; }
echo -e $GREEN"执行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"创建软链接.."$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创建失败,请自行创建链接.." 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目录不存在,开始创建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创建成功!"$END;}
! [ -e ${cafile_path}serial ] && { echo -n 01 > ${cafile_path}serial;echo -e $GREEN"serial创建成功!"$END;}
! [ -e ${cafile_path}crlnumber ] && { echo -n 01 > ${cafile_path}crlnumber;echo -e $GREEN"crlnumber创建成功!"$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; }
#生成的证书前面带了一堆状态信息
#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 "是否需要继续生成证书?" 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}目录下,修改好权限,然后再执行安装"$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="请选择您要执行的操作!:"
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 "是否需要继续生成下一个网站?" 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主机上创建目录
mkdir /data/serverX #X默认是1,除非之前也创建过/data/server1,会变成2
chown nginx.nginx /data/serverX
#在123主机上复制
scp -r /root/wordpress 192.168.32.125:/data/serverX/