lnmp环境不重新编译php安装postgresql扩展(pgsql和pdo_pgsql)

新项目的服务器使用的是lnmp环境,已经把mysql换成了postgresql,那么必须让php支持pgsql扩展。

为了不重新编译php,使用phpize工具进行追加。

1.下载php7安装包

访问php官方下载页,找到自己对应的php版本:https://secure.php.net/downloads.php
wget //cn2.php.net/distributions/php-7.0.30.tar.gz

2.解压并进入扩展目录

tar xzf php-7.0.30.tar.gz
cd php-7.0.30/ext/pgsql

3.运行phpize(我的php安装目录为/usr/local/php/)

/usr/local/php/bin/phpize

4.编译安装

./configure --with-php-config=/usr/local/php/bin/php-config
make && make install

5.修改php配置文件php.ini,添加pgsql.so模块

vi /usr/local/php/etc/php.ini
添加
extension=pgsql.so
extension=pdo_pgsql.so

6.重启php后,检查是否有pgsql模块

php -m

注:pdo_pgsql操作同上

docker 容器搭建 lnmp 环境小记

1.阿里云容器地址

https://cr.console.aliyun.com

2.创建镜像仓库

3.虚拟机修改docker源

修改文件:/etc/docker/daemon.json

内容:

{
"registry-mirrors": ["https://78zjyej0.mirror.aliyuncs.com"]
}

4.虚拟机登录仓库账号

docker login --username= registry.cn-shenzhen.aliyuncs.com

输入账号密码,账号为阿里云账号,密码是在仓库那里另外设置的密码
有时login会出现这个问题: x509: certificate has expired or is not yet valid

这个问题是由于虚机的系统时间没有校正导致的,使用date命令查看时间是否为本地时间 ,使用命令 ntpdate cn.pool.ntp.org 校正时间,如果提示命令不存在,使用命令安装 yum instal ntp ,再使用 date 命令进行查看,确保时间为本地时间,最后重新使用 docker login 命令,输入密码即可。

5.拉取php镜像

docker pull php:7.2-fpm

尝试过很多php镜像,发现还是这个好用一点,配置文件分割清析在 /usr/local/etc 下面,php相关命令较全,在 /usr/local/bin 下可以看到很多命令,包括 phpize php-config 等等,而且改配置立即生效。

6.xdebug扩展

使用镜像开启一个容器 docker run -itd --name php php:7.2-fpm ,进入容器 docker exec -it php bash ,
使用 php -m 命令可看相关模块,笔者自己安装了 xdebug 扩展,使用命令 php -i > phpinfo.txt 获取到环境信息,复制文件里的内容到这个网址获取对应版本的 xdebug https://xdebug.org/wizard.php
,文件是下载到宿主机的,要拷贝文件到docker容器中, docker cp filename containerid:target_file_path ,到容器中解压文件并进入目录

/usr/local/bin/phpize 
./configure --with-php-config=/usr/local/bin/php-config
make && make install

安装完成,添加配置,在目录 /usr/local/etc/php/conf.d 下添加xdebug.ini文件,内容为

;zend_extension=/usr/local/lib/php/extensions/no-debug-non-zts-20170718/xdebug.so

;xdebug.remote_enable=1
;xdebug.idekey="PHPSTORM"
;xdebug.remote_connect_back=1
;xdebug.remote_port=9900
;xdebug.remote_log="/tmp/xdebug_log/"

使用的时间把”;”删除,使用xdebug生效, php -m 查看安装模块是否有xdebug。如果要安装其他模块,安装命令和配置添加类似,可以下载相应的php安装源码cp到虚拟机安装所需的扩展。(笔者曾经试过自己安装在一个centos容器中安装php环境,跑到最后达到了1.5G,最重要的是fileinfo这个扩展安装不了,提示内存不足,在网上找了很多方法都不行,最后放弃了,直接找现成的php容器)

7.提交镜像

回到宿主机,为保留刚才做的修改,所以重新创建一个镜像 git commit -m 'update php image' songzw/php-fpm:v1 ,此时使用 git images 可以看到多了一个 songzw/php-fpm:v2 镜像

8.提交镜像到阿里仓库

docker tag [ImageId] registry.cn-shenzhen.aliyuncs.com/songzw/php:[镜像版本号] 把仓库修改到阿里, docker push registry.cn-shenzhen.aliyuncs.com/songzw/php:[镜像版本号] 完成推送。

9.在php容器中需要安装composer才能安装扩展包,使用composer命令时要用到git,zip,unzip命令,所以要先 apt-get update , apt-get install git zip upzip ,重新构建镜像。

10.docker-compose构建nginx

./nginx/Dockerfile

from nginx
COPY ./*.conf /etc/nginx/conf.d/
run mkdir -p /var/nginx/logs/access /var/nginx/logs/error && chmod -R 777 /var/nginx
CMD nginx

nginx如果本地没有,则会先从远程仓库中拉取,将本地的conf配置文件拷贝到容器,在容器中创建目录并且授权,这个不是必须的,因为我本地的conf文件里配置的日志文件和错误文件是在这个目录,所有本地也要先有这个目录,如果容器起不来,使用docker logs containerid来查看日志,有可能是这个目录问题导致的,最后以nginx进程来运行容器,这个放到docker-compose里面没有生效,导致容器起不来。

11.docker-compose构建mysql

./mysql/Dockerfile

from mysql:5.6
COPY ./*.cnf /etc/mysql/mysql.conf.d/

需要在mysql目录下 touch my.cnf ,里面内容为自定义配置,可以为空,mysql:5.6镜像如果本地不存在也是从远程拉取。

12.docker-compose构建php

from songzw/php-fpm:v5
COPY *.conf /usr/local/etc/php-fpm.d/
COPY *.ini /usr/local/etc/php/conf.d/
run chown -R www-data.www-data /var/www

其中songzw/php-fpm:v5是笔者从php:7.2-fpm拉取下来进行重新构建的镜像,要创建文件 touch my.conftouch my.ini ,这样可以添加自定义配置,/var/www修改属主是因为会出现缓存文件的写权限问题

13.docker-compose.yml

最后呈现docker-compose.yml文件内容

mysql:
  build: ./mysql/
  volumes:
   - /var/mysql/data:/var/lib/mysql
   - /var/mysql/logs:/var/log/mysql
  expose:
   - "3306"
  ports:
   - 3306:3306
  env_file:
   - ./env

 php:
  build: ./php/
  volumes:
   - /var/www/html:/var/www/html
  expose:
   - "9000"
  links:
   - mysql
  command: php-fpm

 nginx:
  build: ./nginx
  volumes_from:
   - php
  volumes:
   - /var/nginx:/var/nginx
  links:
   - php
  ports:
   - "80:80"

使用 docker-compose up -ddocker-compose down 便可以搭建和销毁环境,其中nginx的配置文件在配置连接php时使用php容器ip或者 fastcgi_pass php:9000 ;,php代码连接mysql数据库时使用mysql容器ip或者别名mysql,即links对应的别名。

LNMP架构 (6) 之 php-fpm的pool、慢执行日志、open_basedir、进程管理

1. php-fpm的pool

为了避免因多站点使用同一个pool时,因为一个站点故障导致pool出问题,进而影响使用同一个pool的其他站点的正常运行,我们有必要对每一个站点设置一个单独的pool。

1.1 为php-fpm配置多个pool

编辑php-fpm配置文件:

[root@host etc]# vim /usr/local/php-fpm/etc/php-fpm.conf  

[www]
listen = /tmp/php-fcgi.sock
#listen = 127.0.0.1:9000
listen.mode = 666
user = php-fpm
group = php-fpm
pm = dynamic
pm.max_children = 50
pm.start_servers = 20
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500
rlimit_files = 1024
……
[zhouqun.com]      //添加新的pool
listen = /tmp/zhouqun.sock
listen.mode = 666
user = php-fpm
group = php-fpm
pm = dynamic
pm.max_children = 50
pm.start_servers = 20
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500
rlimit_files = 1024

1.2 语法检测

[root@host etc]# /usr/local/php-fpm/sbin/php-fpm -t
[12-Sep-2017 23:26:57] NOTICE: configuration file /usr/local/php-fpm/etc/php-fpm.conf test is successful

1.3 重新加载配置文件

[root@host etc]# /etc/init.d/php-fpm reload
Reload service php-fpm  done

1.4 查看进程

[root@host etc]# ps aux |grep php-fpm

php-fpm  6222  0.0  0.4 226640  4716 ?        S    16:10  0:00 php-fpm: pool www
php-fpm  6223  0.0  0.4 226640  4712 ?        S    16:10  0:00 php-fpm: pool zhouqun.com

1.5 为站点设置pool

[root@host vhost]# vim /usr/local/nginx/conf/vhost/aaa.com.conf

location ~ .php$
    {
        include fastcgi_params;
        fastcgi_pass unix:/tmp/zhouqun.sock;    //把fastcgi_pass地址改为和php-fpm.conf中一样的地址就可以
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /data/wwwroot/default$fastcgi_script_name;
    }

1.6 添加php-fpm.conf子配置文件

为了便于管理,可以将php-fpm中的每个pool单独进行管理。进行如下操作,添加php-fpm子配置文件:

[root@host vhost]# vim /usr/local/php-fpm/etc/php-fpm.conf

[global]
pid = /usr/local/php-fpm/var/run/php-fpm.pid
error_log = /usr/local/php-fpm/var/log/php-fpm.log
include = etc/php-fpm.d/*.conf   //添加
#在全局变量版块添加参数“include = etc/php-fpm.d/*.conf”。然后可以清除php-fpm配置文件中其他参数,再到php-fpm.d目录下进行单独设置。

1.7 创建指定目录

[root@host vhost]# cd /usr/local/php-fpm/etc/
[root@host etc]# mkdir php-fpm.d

[root@host etc]# cd php-fpm.d/

1.8 创建php-fpm子配置文件

[root@host php-fpm.d]# vim www.conf
[www]
listen = /tmp/php-fcgi.sock
listen.mode = 666
user = php-fpm
group = php-fpm
pm = dynamic
pm.max_children = 50
pm.start_servers = 20
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500
rlimit_files = 1024

[root@host php-fpm.d]# vim zhouqun.conf
[zhouqun.com]
listen = /tmp/zhouqun.sock
listen.mode = 666
user = php-fpm
group = php-fpm
pm = dynamic
pm.max_children = 50
pm.start_servers = 20
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500
rlimit_files = 1024

1.9 检查语法错误并重启:

[root@host php-fpm.d]# /usr/local/php-fpm/sbin/php-fpm -t
[16-Aug-2017 16:49:17] NOTICE: configuration file /usr/local/php-fpm/etc/php-fpm.conf test is successful

[root@host php-fpm.d]# /etc/init.d/php-fpm reload
Reload service php-fpm  done

查看php-fpm进程信息还是使用ps命令。

2. php-fpm慢执行日志

php网站莫名的访问很慢,可以通过慢执行日志找到症结所在,所以满日志非常重要,php网站强烈推荐使用LNMP架构搭建。

2.1 开启慢执行日志:

[root@host php-fpm.d]# vim /usr/local/php-fpm/etc/php-fpm.d/www.conf
……
request_slowlog_timeout = 1                //当请求超过1秒开始记录日志
slowlog = /usr/local/php-fpm/var/log/www-slow.log           //日志存放地址
检测并重加载
[root@host php-fpm.d]# /usr/local/php-fpm/sbin/php-fpm -t
[root@host php-fpm.d]# /etc/init.d/php-fpm reload

2.2 试验

在使用www pool的站点添加文件:

[root@host php-fpm.d]# vim /data/wwwroot/test.com/sleep.php   //创建一个.php文件,故意让它休眠2秒,让它运行缓慢
<?php
echo "test slow log";
sleep(2);     
echo "done";
?>

2.3 检测

[root@host php-fpm.d]# curl -x127.0.0.1:80 test.com/sleep.php 
test slow log done

2.4 查看慢日志

[root@host php-fpm.d]# tail /usr/local/php-fpm/var/log/www-slow.log 

[12-Sep-2017 23:42:23]  [pool www] pid 4236
script_filename = /data/wwwroot/test.com/sleep.php
[0x00007fe027r0e2f5] sleep() /data/wwwroot/test.com/sleep.php:3      //显示文件的第三行导致的访问慢,因为第三行就是sleep命令

3. php-fpm定义open_basedir

在php-fpm服务中,当一台服务器跑多个网站时,用open_basedir限定各个站点所能访问的服务器上的目录的范围,可以针对每个pool设定open _ basedir。

3.1 核心配置参数:

[root@host ~]# vim /usr/local/php-fpm/etc/php-fpm.d/www.conf  
……
php_admin_value[open_basedir]=/data/wwwroot/test.com:/tmp/     //修改

3.2 创建测试PHP脚本

[root@host php-fpm.d]# vim /data/wwwroot/test.com/1.php
<?php
echo "This is a test php of open_basedir";

3.3 测试

[root@host php-fpm.d]# curl -x127.0.0.1:80 test.com/1.php
This is a test php of open_basedir

4. php-fpm进程管理

php-fpm中pool配置参数解析:

[root@host php-fpm.d]# vim www.conf
[www]
listen = /tmp/php-fcgi.sock
listen.mode = 666
user = php-fpm
group = php-fpm
pm = dynamic
#设置进程启动方式(dynamic表示动态,static表示静态)
#只有此处设置为dynamic,下面的配置才生效
pm.max_children = 50   //最多可启动的子进程数量
pm.start_servers = 20    //设定初始启动的进程数量
pm.min_spare_servers = 5      //表示php-fpm空闲时最少要有几个子进程
pm.max_spare_servers = 35   //表示php-fpm空闲时最多要有几个子进程
pm.max_requests = 500          //表示一个子进程最多可接受多少个请求
rlimit_files = 1024                     //表示每个子进程打开的多少个文件句柄
request_slowlog_timeout = 1    //当请求超过1秒开始记录日志
slowlog = /usr/local/php-fpm/var/log/www-slow.log      //日志存放地址
php_admin_value[open_basedir]=/data/wwwroot/test.com:/tmp/

LNMP架构 (5) 之 Nginx负载均衡、ssl原理、生成ssl密钥对、配置ssl

1. Nginx负载均衡

Nginx负载均衡就是指 当代理服务器将自定义的域名解析到多个指定IP时,通过upstream模块来保证用户可以通过代理服务器正常访问各个IP(反向代理多台服务器就是负载均衡)。

1.1 负载均衡配置参数

[root@host ~]# vim /usr/local/nginx/conf/vhost/load.conf
upstream qq
#自定义域名
{
    ip_hash;
#目的是为了保证同一个用户始终保持在同一台机器上
#还有就是为了当域名指向多个IP时,保证每个用户始终解析到同一IP
    server 61.135.157.156:80;
    server 125.39.240.113:80;
#指定web服务器的IP
}
server
{
    listen 80;
    server_name www.qq.com;
    location /
    {
        proxy_pass      http://qq;
        proxy_set_header Host  $host;
        proxy_set_header X-Real-IP      $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

1.2 检测

代理前

[root@host ~]# curl -x127.0.0.1:80 www.qq.com 
This is the default directory.

#没使用代理时,会直接解析到默认的虚拟主机。

代理后

[root@host ~]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@host ~]# /usr/local/nginx/sbin/nginx -s reload
[root@host ~]# curl -x127.0.0.1:80 www.qq.com
……
#使用代理后,会解析到代理服务器所指向的IP的网页代码

1.3 dig命令

dig命令是常用域名的解析工具,可以寻找域名的全部IP。

如果服务器中没有安装命令

[root@host ~]# yum install -y bind-utils

解析qq网站的全部IP

[root@host ~]# dig www.qq.com

;; ANSWER SECTION:
www.qq.com.        138    IN    A    61.135.157.156
www.qq.com.        138    IN    A    125.39.240.113

;; Query time: 12 msec
;; SERVER: 119.29.29.29#53(119.29.29.29)
;; WHEN: 二 9月 12 22:44:23 CST 2017
;; MSG SIZE  rcvd: 61

2. ssl原理

SSL(Secure Sockets Layer 安//全//套接层)协议,及其继任者TLS(Transport Layer Security传输层安全)协议,是为网络通信提供安全及数据完整性的一种安全协议。

2.1 http、https、tcp

  • HTTP超文本传输协议(HyperText Transfer Protocol)是互联网上应用最为广泛的一种网络协议。
  • HTTPS(全称:Hyper Text Transfer Protocol over Secure Socket Layer),简单讲是HTTP的安全加密版。
  • HTTP默认的端口号为80,HTTPS的端口号为443。
  • TCP(Transmission Control Protocol 传输控制协议)是一种面向连接的、可靠的、基于字节流的传输层通信协议。默认监听80端口。
  • http是应用层协议, tcp是传输层。 http使用tcp传输文本数据; http只是定义了tcp数据的解析方式

2.2 SSL工作流程

  • 浏览器发送一个https的请求给服务器;
  • 服务器要有一套数字证书,可以自己制作(后面的操作就是阿铭自己制作的证书),也可以向组织申请,区别就是自己颁发的证书需要客户端验证通过,才可以继续访问,而使用受信任的公司申请的证书则不会弹出>提示页面,这套证书其实就是一对公钥和私钥;
  • 服务器会把公钥传输给客户端;
  • 客户端(浏览器)收到公钥后,会验证其是否合法有效,无效会有警告提醒,有效则会生成一串随机数,并用收到的公钥加密;
  • 客户端把加密后的随机字符串传输给服务器;
  • 服务器收到加密随机字符串后,先用私钥解密(公钥加密,私钥解密),获取到这一串随机数后,再用这串随机字符串加密传输的数据(该加密为对称加密,所谓对称加密,就是将数据和私钥也就是这个随机字符串>通过某种算法混合在一起,这样除非知道私钥,否则无法获取数据内容);
  • 服务器把加密后的数据传输给客户端;
  • 客户端收到数据后,再用自己的私钥也就是那个随机字符串解密;

3. 生成ssl密钥对

SSL证书就是一对公钥和私钥。

3.1 准备工具

如果虚拟机中没有此工具,手动安装:

[root@host ~]# yum install -y openssl

3.2 创建私钥

[root@host ~]# cd /usr/local/nginx/conf/

[root@host conf]# openssl genrsa -des3 -out tmp.key 2048  //生成SSL密钥
Generating RSA private key, 2048 bit long modulus
....................................................................................+++
...............................................................+++
e is 65537 (0x10001)
Enter pass phrase for tmp.key:
Verifying - Enter pass phrase for tmp.key:   //密钥需要我们设置密码,一般我们都不需要再设置密码,所以要转换一下key,取消密码

[root@host conf]# openssl rsa -in tmp.key -out host.key  //转换一下key,将tmp.key 转换为没密码的host.key

Enter pass phrase for tmp.key:
writing RSA key

[root@host conf]# rm -f tmp.key  //删除tmp.key

3.3 自己生成证书

[root@host conf]# openssl req -new -key host.key -out host.csr   //自己生成证书请求文件,需要拿这个私钥一起生成证书
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) [XX]:11
State or Province Name (full name) []:BeiJing
Locality Name (eg, city) [Default City]:BeiJing
Organization Name (eg, company) [Default Company Ltd]:BeiJing
Organizational Unit Name (eg, section) []:BeiJing
Common Name (eg, your name or your server's hostname) []:host
Email Address []:zhouqunic@qq.com
#以上是配置证书信息,因为是自己颁发给自己的证书,就随意瞎填或者干脆Enter跳过,如果是正式应用在自己的网站上,最好规范填写。

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:123456
An optional company name []:123456

3.4 创建公钥

[root@host conf]# openssl x509 -req -days 365 -in host.csr -signkey host.key -out host.crt  //这里的aminglinux.crt为公钥

Signature ok
subject=/C=11/ST=BeiJing/L=BeiJing/O=BeiJing/OU=BeiJing/CN=host/emailAddress=zhouqunic@qq.com
Getting Private key

4. Nginx配置ssl

4.1 配置文件

[root@host conf]# cd vhost/

[root@host vhost]# vim ssl.conf
server
{
    listen 443;
    server_name zhouqun.com;
    index index.html index.php;
    root /data/wwwroot/zhouquncom;
    ssl on;      //开启ssl
    ssl_certificate host.crt;     //配置公钥
    ssl_certificate_key host.key;        //配置私钥
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;      ///配置协议
}

[root@host vhost]# mkdir /data/wwwroot/zhouqun.com

4.2 检测

[root@host conf]# /usr/local/nginx/sbin/nginx -t
nginx: [emerg] unknown directive "ssl" in /usr/local/nginx/conf/vhost/ssl.conf:7       //报错了
nginx: configuration file /usr/local/nginx/conf/nginx.conf test failed

4.3 报错 unknown directive “ssl” 未识别ssl配置,需要重新编译nginx,加上–with-http_ssl_module

[root@host conf]# cd /usr/local/src/nginx-1.12.1/

[root@host nginx-1.12.1]# ./configure --prefix=/usr/local/nginx --with-http_ssl_module  

[root@host conf]# make
[root@host conf]# make install

[root@host nginx-1.12.1]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

[root@host nginx-1.12.1]# /etc/init.d/nginx restart
Restarting nginx (via systemctl):                          [  OK  ]

[root@host nginx-1.12.1]# netstat -lntp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address          Foreign Address        State      PID/Program name    
tcp        0      0 0.0.0.0:80              0.0.0.0:*              LISTEN      5991/nginx: master  
tcp        0      0 0.0.0.0:22              0.0.0.0:*              LISTEN      1735/sshd          
tcp        0      0 127.0.0.1:25            0.0.0.0:*              LISTEN      2040/master        
tcp        0      0 0.0.0.0:443            0.0.0.0:*              LISTEN      5991/nginx: master  
tcp6      0      0 :::3306                :::*                    LISTEN      1990/mysqld        
tcp6      0      0 :::22                  :::*                    LISTEN      1735/sshd          
tcp6      0      0 ::1:25                  :::*                    LISTEN      2040/master  

nginx监听80和443端口。

4.4 测试

[root@host nginx-1.12.1]# cd /data/wwwroot/zhouqun.com/

[root@host adai.com]# vim index.html

This is ssl.

4.5 添加本地域名:

[root@host adai.com]# vim /etc/hosts
127.0.0.1  zhouqun.com

[root@host vhost]# curl https://zhouqun.com/
curl: (60) Peer's certificate issuer has been marked as not trusted by the user.
More details here: http://curl.haxx.se/docs/sslcerts.html

curl performs SSL certificate verification by default, using a "bundle"
of Certificate Authority (CA) public keys (CA certs). If the default
bundle file isn't adequate, you can specify an alternate file
using the --cacert option.
If this HTTPS server uses a certificate signed by a CA represented in
the bundle, the certificate verification probably failed due to a
problem with the certificate (it might be expired, or the name might
not match the domain name in the URL).
If you'd like to turn off curl's verification of the certificate, use
the -k (or --insecure) option.

因为该证书是自己创建的,没有符合https组织的规范,不能被正确识别,如果换上正规的证书,就没问题了。

所以,如果要使用浏览器检测,那么进行该测试之前,需要更改Windows的hosts文件,不然就会证书出错的。

LNMP架构 (4) 之 Nginx的防盗链、访问控制、解析php相关配置

1. Nginx防盗链

Nginx防盗链可结合日志管理一起配置,因为该配置也要使用location板块

[root@host ~]# vim /usr/local/nginx/conf/vhost/test.com.conf
……
location ~* ^.+.(gif|jpg|png|swf|flv|rar|zip|doc|pdf|gz|bz2|jpeg|bmp|xls)$
{
    expires 7d;
    valid_referers none blocked server_names  *.test.com ;
    #定义referer白名单
    if ($invalid_referer) {
        return 403;
    #if函数的意思是:如果不是白名单内的域名,返回值:403
    }
    access_log off;
}
……

[root@host ~]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@host ~]# /usr/local/nginx/sbin/nginx -s reload

检查
[root@host ~]# curl -e "http://www.baidu.com/1.txt" -x127.0.0.1:80 -I test.com/baidu.png
HTTP/1.1 403 Forbidden
Server: nginx/1.12.1
Date: Mon, 11 Sep 2017 11:25:47 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
访问被拒绝,防盗链生效

2. Nginx访问控制

只允许几个指定IP通过访问/admin/目录的请求

[root@host ~]# vim /usr/local/nginx/conf/vhost/test.com.conf 
……
location /admin/
    {
#设置IP白名单
    allow 192.168.8.132;
    allow 127.0.0.1;
    deny all;

    }


[root@host ~]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@host ~]# /usr/local/nginx/sbin/nginx -s reload

创建目录

[root@host ~]# mkdir /data/wwwroot/test.com/admin
[root@host ~]#  echo “test,test”>/data/wwwroot/test.com/admin/1.html

测试

[root@host ~]# curl -x127.0.0.1:80  test.com/admin/1.html
“test,test”
[root@host ~]# curl -x192.168.2.107:80  test.com/admin/1.html
“test,test”

访问控制

#正则匹配
location ~ .*(abc|image)/.*.php$
{
        deny all;
}


#user_agent限制
if ($http_user_agent ~ 'Spider/3.0|YoudaoBot|Tomato')
{
      return 403;
}

#deny all和return 403效果一样

#12.15 Nginx解析php相关配置 核心配置文件

[root@host ~]# vim /usr/local/nginx/conf/vhost/test.com.conf
……
location ~ .php$
    {
        include fastcgi_params;
#fastcgi_pass 127.0.0.1:9000
        fastcgi_pass unix:/tmp/php-fcgi.sock;
#fastcgi_pass 有两种监听格式,要保证Nginx和php-fpm中格式是一致的,否则会报502错误
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /data/wwwroot/test.com$fastcgi_script_name;
#fastcgi _param SCRIPT _FILENAME所在行的路径要和root路径一致
    }

3. Nginx代理

在计算机网络中,反向代理是代理服务器的一种。它根据客户端的请求,从后端的服务器上获取资源,然后再将这些资源返回给客户端。与前向代理不同,前向代理作为一个媒介将互联网上获取的资源返回给相关联的客户端,而反向代理是在服务器端作为代理使用,而不是客户端。

3.1 Nginx作为反向代理的特点

  • 接收用户请求是异步的,即先将用户请求全部接收下来,再一次性发送后后端web服务器,极大的减轻后端web服务器的压力;

  • nginx代理和后端web服务器间无需长连接;
    发送响应报文时,是边接收来自后端web服务器的数据,边发送给客户端的;

  • 调度灵活。NGINX工作在网络协议栈的第七层,能够对HTTP应用请求进行解析和分流,支持比较复杂的正则规则,具有更优化的负载均衡效果。

  • 网络依赖型低。NGINX对网络的依赖程度非常低,理论上讲,只要能够ping通就可以实施负载均衡,而且可以有效区分内网和外网流量。

  • 支持服务器检测。NGINX能够根据应用服务器处理页面返回的状态码、超时信息等检测服务器是否出现故障,并及时返回错误的请求重新提交到其它节点上。

3.2 工作原理

Nginx代理是在一台代理服务器中自定义一个域名,该域名指向一个IP,然后将用户的请求通过这台代理服务器访问指定的IP所对应的web服务器。

3.3 进入虚拟主机目录

[root@host ~]# cd /usr/local/nginx/conf/vhost/

3.4 创建代理服务器

[root@host vhost]# vim proxy.conf
server
{
    listen 80;
    server_name ask.apelearn.com;
#定义域名
    location /
    {
        proxy_pass      http://121.201.9.155/;
#指定被代理(被访问)的IP(web服务器IP)
        proxy_set_header Host  $host;
#$host指的是代理服务器的servername(也是被代理IP的域名)
        proxy_set_header X-Real-IP      $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}
设置好以后,就可以访问aminglinux论坛了

3.5 检测验证

#之前
[root@host vhost]# curl -x127.0.0.1:80 ask.apelearn.com/robots.txt
<html>
<head><title>404 Not Found</title></head>
<body bgcolor="white">
<center><h1>404 Not Found</h1></center>
<hr><center>nginx/1.12.1</center>
</body>
</html>

#之后
[root@host vhost]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@host vhost]# /usr/local/nginx/sbin/nginx -s reload


[root@host vhost]# curl -x127.0.0.1:80 ask.apelearn.com/robots.txt
#
# robots.txt for MiWen
#

User-agent: *

Disallow: /?/admin/
Disallow: /?/people/
Disallow: /?/question/
Disallow: /account/
Disallow: /app/
Disallow: /cache/

LNMP架构 (3) 之 Nginx访问日志、日志切割、静态文件不记录日志和过期时间

1. Nginx访问日志

1.1 日志格式

[root@host ~]# vim /usr/local/nginx/conf/nginx.conf   //搜索log_format
... ...
log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]'
    ' $host "$request_uri" $status'
    ' "$http_referer" "$http_user_agent"';
#combined_realip是日志名称 
# 后面带引号和$的是日志内容

1.2 日志格式参数注释

未分类

1.3 定义虚拟主机日志格式(一定要先定义nginx.conf中的日志格式,才能在这里调用和再定义)

[root@host ~]# cd /usr/local/nginx/conf/vhost/
[root@host vhost]# ls
aaa.com.conf  test.com.conf

[root@host vhost]# vim aaa.com.conf     //定义aaa.com.conf日志格式 
……
access_log /tmp/aaa.com.log combined_realip;
#指定日志位置和格式

检查错误:
[root@host vhost]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

1.4 检查

[root@host vhost]# curl -x127.0.0.1:80 aaacom 
This is aaa.com
[root@host vhost]# cat /tmp/aaa.com.log 
127.0.0.1 - [8/Sep/2017:22:39:68 +0800] aaa.com "/" 200 "-" "curl/7.29.0"

2. Nginx日志切割

因为Nginx没有自带的日志切割工具,所以需要借助系统日志切割命令或自己编写日志切割脚本。

2.1 日志切割脚本

以后把所有的shell脚本统一保存位置:/usr/local/sbin/

[root@host vhost]# vim /usr/local/sbin/nginx_log_rotate.sh

#! /bin/bash
d=`date -d "-1 day" +%Y%m%d` 
#定义切割时间(切割一天前的日志)
logdir="/tmp/"
#此处指定要切割的日志路径(该路径来自虚拟主机配置文件)
nginx_pid="/usr/local/nginx/logs/nginx.pid"
#调用pid的目的是为了执行命令:/bin/kill -HUP `cat $nginx_pid`
#该命令相当于命令:nginx -s reload(重新加载文件),确保与虚拟主机配置文件变更保持同步
#该地址来自nginx配置文件
cd $logdir
for log in `ls *.log`
do
    mv $log $log-$d
done
#这里使用通配进行循环,对所有符合条件的日志文件进行切割
/bin/kill -HUP `cat $nginx_pid`
#执行此命令进行重新加载生成新的日志文件来记录新的日志

2.2 执行该脚本

[root@host vhost]# sh -x /usr/local/sbin/nginx_log_rotate.sh
++ date -d '-1 day' +%Y%m%d
+ d=20170909
+ logdir=/tmp/
+ nginx_pid=/usr/local/nginx/logs/nginx.pid
+ cd /tmp/
++ ls test.com.log yum.log
+ for log in '`ls *.log`'
+ mv test.com.log test.com.log-20170909
+ for log in '`ls *.log`'
+ mv yum.log yum.log-20170909
++ cat /usr/local/nginx/logs/nginx.pid
+ /bin/kill -HUP 59154

2.3添加到系统任务计划

[root@host vhost]# vim /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed

0 3 * * * /bin/bash /usr/local/sbin/nginx_log_rotate.sh
#每天凌晨3点切割一次前一天日志

[root@host vhost]# chmod +x /usr/local/sbin/nginx_log_rotate.sh  //加上可执行权限

3. 静态文件不记录日志和过期时间

3.1 核心配置参数

[root@host vhost]# vim test.com.conf
location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$
    #匹配文件类型
    {
          expires      7d;
          #过期时间为7天
          access_log off;
          #不记录该类型文件的访问日志
    }
location ~ .*.(js|css)$
    {
          expires      12h;
          #过期时间为12小时
          access_log off;
          #不记录该类型文件的访问日志
    }
    access_log /tmp/test.com.log combined_realip;
    #指定日志位置及格式

3.2 检测

[root@host vhost]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@host vhost]# /usr/local/nginx/sbin/nginx -s reload

访问index.html文件
[root@host vhost]# !curl
curl -x127.0.0.1:80 test.com
This is test.com

[root@host vhost]# !cat
cat /tmp/test.com.log 
127.0.0.1 - [9/Sep/2017:00:12:26 +0800] test.com "/" 200 "-" "curl/7.29.0"
#有日志

访问baidu.png文件
[root@host test.com]# curl -x127.0.0.1:80 test.com/baidu.png -I
HTTP/1.1 200 OK
Server: nginx/1.12.1
Date: Sat, 9 Aug 2017 09:47:57 GMT
Content-Type: image/png
Content-Length: 3706
Last-Modified: Sat, 09 Sep 2017 01:13:35 GMT
Connection: keep-alive
ETag: "59805459-e7a"
Expires: Sat, 09 Sep 2017 00:47:46 GMT
Cache-Control: max-age=604800
Accept-Ranges: bytes
#max-age=604800s=7天,即该文件缓存的过期时间为7天!

[root@host test.com]# cat /tmp/test.com.log 
127.0.0.1 - [9/Sep/2017:00:13:39+0800] test.com "/" 200 "-" "curl/7.29.0"
#无该文件的访问日志!!!

LNMP架构 (2)之 Nginx安装、默认虚拟主机、用户认证、域名重定向、配置文件详解

5. Nginx安装

5.1 准备

[root@host ~]# cd /usr/local/src/

[root@host src]# wget http://nginx.org/download/nginx-1.12.1.tar.gz

[root@host src]# tar zxvf nginx-1.12.1.tar.gz 

5.2 安装

[root@host src]# cd nginx-1.12.1/

[root@host nginx-1.12.1]# ./configure --prefix=/usr/local/nginx   //如果需要支持某模块,可以在此添加,如HTTPS、SSL等,我们这里就先不安装,后面再编译进去

[root@host nginx-1.12.1]# make && make install  //编译
[root@host nginx-1.12.1]# echo $?           //检查
0
[root@host nginx-1.12.1]# cd /usr/local/nginx/
[root@host nginx]# ls
conf  html  logs  sbin

5.3 配置

添加nginx到启动服务

[root@host nginx]# vim /etc/init.d/nginx   //创建启动脚本,写入以下代码

#!/bin/bash
# chkconfig: - 30 21
# description: http service.
# Source Function Library
. /etc/init.d/functions
# Nginx Settings
NGINX_SBIN="/usr/local/nginx/sbin/nginx"
NGINX_CONF="/usr/local/nginx/conf/nginx.conf"
NGINX_PID="/usr/local/nginx/logs/nginx.pid"
RETVAL=0
prog="Nginx"
start() 
{
    echo -n $"Starting $prog: "
    mkdir -p /dev/shm/nginx_temp
    daemon $NGINX_SBIN -c $NGINX_CONF
    RETVAL=$?
    echo
    return $RETVAL
}
stop() 
{
    echo -n $"Stopping $prog: "
    killproc -p $NGINX_PID $NGINX_SBIN -TERM
    rm -rf /dev/shm/nginx_temp
    RETVAL=$?
    echo
    return $RETVAL
}
reload()
{
    echo -n $"Reloading $prog: "
    killproc -p $NGINX_PID $NGINX_SBIN -HUP
    RETVAL=$?
    echo
    return $RETVAL
}
restart()
{
    stop
    start
}
configtest()
{
    $NGINX_SBIN -c $NGINX_CONF -t
    return 0
}
case "$1" in
  start)
        start
        ;;
  stop)
        stop
        ;;
  reload)
        reload
        ;;
  restart)
        restart
        ;;
  configtest)
        configtest
        ;;
  *)
        echo $"Usage: $0 {start|stop|reload|restart|configtest}"
        RETVAL=1
esac
exit $RETVAL


检查语法
[root@host nginx]# /usr/local/nginx/sbin/nginx -t  
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

更改权限
[root@host nginx]# chmod 755 /etc/init.d/nginx

添加到系统服务
[root@host nginx]# chkconfig --add nginx
[root@host nginx]# chkconfig nginx on

更改Nginx的配置文件

[root@host nginx]# cd /usr/local/nginx/conf/    
[root@host conf]# mv nginx.conf nginx.conf.bak  //把Nginx自带脚本存做备份,创建自己的脚本

[root@host conf]# vim nginx.conf    //写入以下内容

user nobody nobody;
#定义启动Nginx服务的用户
worker_processes 2;
#定义子进程数
error_log /usr/local/nginx/logs/nginx_error.log crit;
pid /usr/local/nginx/logs/nginx.pid;
worker_rlimit_nofile 51200;
#指定Nginx最多可打开的文件数
events
{
    use epoll;
    worker_connections 6000;
#进程最大连接数
}

http
{
    include mime.types;
    default_type application/octet-stream;
    server_names_hash_bucket_size 3526;
    server_names_hash_max_size 4096;
    log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]'
    ' $host "$request_uri" $status'
    ' "$http_referer" "$http_user_agent"';
    sendfile on;
    tcp_nopush on;
    keepalive_timeout 30;
    client_header_timeout 3m;
    client_body_timeout 3m;
    send_timeout 3m;
    connection_pool_size 256;
    client_header_buffer_size 1k;
    large_client_header_buffers 8 4k;
    request_pool_size 4k;
    output_buffers 4 32k;
    postpone_output 1460;
    client_max_body_size 10m;
    client_body_buffer_size 256k;
    client_body_temp_path /usr/local/nginx/client_body_temp;
    proxy_temp_path /usr/local/nginx/proxy_temp;
    fastcgi_temp_path /usr/local/nginx/fastcgi_temp;
    fastcgi_intercept_errors on;
    tcp_nodelay on;
    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 8k;
    gzip_comp_level 5;
    gzip_http_version 1.1;
    gzip_types text/plain application/x-javascript text/css text/htm 
    application/xml;
    server
    {
        listen 80;
        server_name localhost;
        index index.html index.htm index.php;
        root /usr/local/nginx/html;
        location ~ .php$
#虚拟主机配置
        {
            include fastcgi_params;
            fastcgi_pass unix:/tmp/php-fcgi.sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME /usr/local/nginx/html$fastcgi_script_name;
#PHP解析配置
        }    
    }
}

检测语法:
[root@host conf]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

启动Nginx服务:
[root@host conf]# /etc/init.d/nginx start
Starting nginx (via systemctl):                            [  确定  ]

查看链接情况
[root@host conf]# ps aux|grep nginx   
root    17603  0.0  0.0  20500  624 ?        Ss  22:57  0:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
nobody  17604  0.0  0.1  22944  3212 ?        S    22:57  0:00 nginx: worker process
nobody  17605  0.0  0.1  22944  3212 ?        S    22:57  0:00 nginx: worker process
root    17607  0.0  0.0 112680  972 pts/1    R+  22:57  0:00 grep --color=auto nginx

[root@host conf]# ps aux|grep php-fpm
root    17609  0.0  0.0 112680  968 pts/1    R+  22:58  0:00 grep --color=auto php-fpm

5.4 检查

[root@host conf]# curl localhost    //curl测试,结果如下,表示正常

<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>

检测PHP解析

[root@host conf]# vim /usr/local/nginx/html/1.php
<?php
echo "test php scripts.";
?>

[root@host conf]# curl localhost/1.php
test php scripts.

6. 默认虚拟主机

6.1 编辑Nginx配置文件,删除原有server内容,添加如下内容:

[root@host ~]# cd /usr/local/nginx/conf
[root@host conf]# vim /usr/local/nginx/conf/nginx.conf
……
include vhost/*.conf;      //创建一个虚拟主机配置文件子目录(相当于增加子虚拟主机)

[root@host conf]# mkdir vhost      //创建配置文件中的目录文件

#nginx配置文件也支持include语法

6.2 增加一台虚拟主机:

[root@host conf]# cd vhost

[root@host vhost]# vim aaa.com.conf    //添加下面这一段

server
{
    listen 80 default_server;     //有'default_server'标记的就是默认虚拟主机
    server_name aaa.com;
    index index.html index.htm index.php;
    root /data/wwwroot/default;
}

[root@host vhost]# mkdir -p /data/wwwroot/default       //创建配置文件中指定的root目录

6.3 为虚拟主机添加内容

进入目录,添加索引页:

[root@host vhost]# cd /data/wwwroot/default

[root@host default]# vim index.html     //编辑一段话

This is the default directory.

[root@host default]# /usr/local/nginx/sbin/nginx -t         //测试语法
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful  

重启动或重加载(两个命令选一个):
[root@host default]# /usr/local/nginx/sbin/nginx -s reload   //重加载
[root@host default]# /usr/local/nginx/sbin/nginx restart       //重启动

6.4 检测

[root@host default]# curl localhost
This is the default directory
[root@host default]# curl -x127.0.0.1:80 123.com
This is the default directory

7. Nginx用户认证

7.1 创建一个虚拟主机

[root@host default]# cd  /usr/local/nginx/conf/vhost/
[root@host vhost]# vim test.com.conf      //写入如下内容

server
{
    listen 80;
    server_name test.com;
    index index.html index.htm index.php;
    root /data/wwwroot/test.com;

location  /       
# / 表示根目录,如果你改成 /admin/,那就是针对目录认证;/admin/test.php,针对php文件认证。
# 指定设置用户认证的目录(还可以设置对目录或者PHP的用户认证)
    {
        auth_basic              "Auth";
#指定用户名
        auth_basic_user_file  /usr/local/nginx/conf/htpasswd;
#指定用户的密码文件
     }
}

7.2 生成密码文件

[root@host vhost]# yum install -y httpd     //需要使用Apache的/usr/local/apache/bin/htpasswd命令,如果已经安装了Apache,可以直接使用,如果没有,需要yum安装
[root@host vhost]# htpasswd -c /usr/local/nginx/conf/htpasswd zhouqun
New password: 
Re-type new password: 
Adding password for user zhouqun
# htpasswd -c创建该密码文件,如果是第二次添加用户,不用加该 -c 选项,所添加的用户名和密码会保存到该文件下。

重新加载

[root@host vhost]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@host vhost]# /usr/local/nginx/sbin/nginx -s reload
# 使用reload的好处是能避免因配置文件中存在错误而无法正常启动, reload不会破坏原有运行环境,所以不适用restart。

7.3 添加配置文件

[root@host vhost]# mkdir /data/wwwroot/test.com    //添加配置文件指定的根目录

[root@host vhost]# echo "This is test.com" >/data/wwwroot/test.com/index.html     //添加索引页

7.4 检查

[root@host vhost]# curl -x127.0.0.1:80 test.com -uzhouqun:123456
This is test.com

#如果不指定用户名和密码,会报错401,原因是:需要用户认证;
#如果为创建虚拟主机根目录会报错404,原因是:找不到指定目录;
#如果指定目录中没有添加索引页(.html或.php文件),会报错404,原因是:文件存在错误。

8. Nginx域名重定向

8.1 编辑虚拟主机配置文件

[root@host vhost]# vim test.com.conf

server
{
    listen 80;
    server_name test.com test2.com test3.com;
#为一个IP配置多个域名,此时权重会改变,如果需要全部跳转到第一个域名,可以使用rewrite模块实现
    index index.html index.htm index.php;
    root /data/wwwroot/test.com;
    if ($host != 'test.com' ) {
        rewrite  ^/(.*)$  http://test.com/$1  permanent;
    }
#使用rewrite模块编写跳转代码
# 实际上,rewrite  ^/(.*)$  http://test.com/$1  = rewrite  http://$host/(.*)$  http://test.com/$1
# ^代替了$host
}

[root@host vhost]# /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@host vhost]# /usr/local/nginx/sbin/nginx -s reload

8.2 检测

[root@host vhost]# curl -x127.0.0.1:80 test2.com -I
HTTP/1.1 301 Moved Permanently
Server: nginx/1.12.1
Date: Fri, 8 Sep 2017 1:20:24 GMT
Content-Type: text/html
Content-Length: 185
Connection: keep-alive
Location: http://test.com/

# 301, 域名跳转,跳转后的地址为  http://test.com/

9. nginx.conf 配置详解

完整的Nginx配置参数中文说明了。

#定义Nginx运行的用户和用户组
user www www;

#nginx进程数,建议设置为等于CPU总核心数。
worker_processes 8;

#全局错误日志定义类型,[ debug | info | notice | warn | error | crit ]
error_log /var/log/nginx/error.log info;

#进程文件
pid /var/run/nginx.pid;

#一个nginx进程打开的最多文件描述符数目,理论值应该是最多打开文件数(系统的值ulimit -n)与nginx进程数相除,但是nginx分配请求并不均匀,所以建议与ulimit -n的值保持一致。
worker_rlimit_nofile 65535;

#工作模式与连接数上限
events
{
#参考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型是Linux 2.6以上版本内核中的高性能网络I/O模型,如果跑在FreeBSD上面,就用kqueue模型。
use epoll;
#单个进程最大连接数(最大连接数=连接数*进程数)
worker_connections 65535;
}

#设定http服务器
http
{
include mime.types; #文件扩展名与文件类型映射表
default_type application/octet-stream; #默认文件类型
#charset utf-8; #默认编码
server_names_hash_bucket_size 128; #服务器名字的hash表大小
client_header_buffer_size 32k; #上传文件大小限制
large_client_header_buffers 4 64k; #设定请求缓
client_max_body_size 8m; #设定请求缓
sendfile on; #开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。
autoindex on; #开启目录列表访问,合适下载服务器,默认关闭。
tcp_nopush on; #防止网络阻塞
tcp_nodelay on; #防止网络阻塞
keepalive_timeout 120; #长连接超时时间,单位是秒

#FastCGI相关参数是为了改善网站的性能:减少资源占用,提高访问速度。下面参数看字面意思都能理解。
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;

#gzip模块设置
gzip on; #开启gzip压缩输出
gzip_min_length 1k; #最小压缩文件大小
gzip_buffers 4 16k; #压缩缓冲区
gzip_http_version 1.0; #压缩版本(默认1.1,前端如果是squid2.5请使用1.0)
gzip_comp_level 2; #压缩等级
gzip_types text/plain application/x-javascript text/css application/xml;
#压缩类型,默认就已经包含text/html,所以下面就不用再写了,写上去也不会有问题,但是会有一个warn。
gzip_vary on;
#limit_zone crawler $binary_remote_addr 10m; #开启限制IP连接数的时候需要使用

upstream blog.ha97.com {
#upstream的负载均衡,weight是权重,可以根据机器配置定义权重。weigth参数表示权值,权值越高被分配到的几率越大。
server 192.168.80.121:80 weight=3;
server 192.168.80.122:80 weight=2;
server 192.168.80.123:80 weight=3;
}

#虚拟主机的配置
server
{
#监听端口
listen 80;
#域名可以有多个,用空格隔开
server_name www.ha97.com ha97.com;
index index.html index.htm index.php;
root /data/www/ha97;
location ~ .*.(php|php5)?$
{
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
#图片缓存时间设置
location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 10d;
}
#JS和CSS缓存时间设置
location ~ .*.(js|css)?$
{
expires 1h;
}
#日志格式设定
log_format access '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" $http_x_forwarded_for';
#定义本虚拟主机的访问日志
access_log /var/log/nginx/ha97access.log access;

#对 "/" 启用反向代理
location / {
proxy_pass http://127.0.0.1:88;
proxy_redirect off;
proxy_set_header X-Real-IP $remote_addr;
#后端的Web服务器可以通过X-Forwarded-For获取用户真实IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#以下是一些反向代理的配置,可选。
proxy_set_header Host $host;
client_max_body_size 10m; #允许客户端请求的最大单文件字节数
client_body_buffer_size 128k; #缓冲区代理缓冲用户端请求的最大字节数,
proxy_connect_timeout 90; #nginx跟后端服务器连接超时时间(代理连接超时)
proxy_send_timeout 90; #后端服务器数据回传时间(代理发送超时)
proxy_read_timeout 90; #连接成功后,后端服务器响应时间(代理接收超时)
proxy_buffer_size 4k; #设置代理服务器(nginx)保存用户头信息的缓冲区大小
proxy_buffers 4 32k; #proxy_buffers缓冲区,网页平均在32k以下的设置
proxy_busy_buffers_size 64k; #高负荷下缓冲大小(proxy_buffers*2)
proxy_temp_file_write_size 64k;
#设定缓存文件夹大小,大于这个值,将从upstream服务器传
}

#设定查看Nginx状态的地址
location /NginxStatus {
stub_status on;
access_log on;
auth_basic "NginxStatus";
auth_basic_user_file conf/htpasswd;
#htpasswd文件的内容可以用apache提供的htpasswd工具来产生。
}

#本地动静分离反向代理配置
#所有jsp的页面均交由tomcat或resin处理
location ~ .(jsp|jspx|do)?$ {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://127.0.0.1:8080;
}
#所有静态文件由nginx直接读取不经过tomcat或resin
location ~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$
{ expires 15d; }
location ~ .*.(js|css)?$
{ expires 1h; }
}
}

更详细的模块参数请参考:http://wiki.nginx.org/Main

LNMP架构 (1) 之 架构介绍、MySQL安装、PHP安装、Nginx介绍

1. LNMP架构介绍

LNMP代表的就是:Linux系统下Nginx+MySQL+PHP这种网站服务器架构。

未分类

  • 和LAMP不同的是,提供web服务的是Nginx
  • 并且php是作为一个独立服务存在的,这个服务叫做php-fpm
  • Nginx直接处理静态请求,动态请求会转发给php-fpm。

2. MySQL安装

2.1 卸载二进制包安装的MySQL

确认MySQL服务运行状态,并停止

[root@host ~]# ps -ef | grep mysql
[root@host ~]# /etc/init.d/mysql.server status
[root@host ~]# /etc/init.d/mysql.server stop

删除MySQL安装时的相关文件

[root@host ~]# rm -rf /usr/local/mysql 
[root@host ~]# rm -rf /etc/init.d/mysqld 
[root@host ~]# rm -rf /data/mysql

2.2 安装MySQL

和之前LAMP环境安装MySQL的方法一样 可以参考前面的文章 LAMP架构及安装配置(https://my.oschina.net/zhouyuntai/blog/1647058) 中的Mysql安装。

3. PHP安装

和LAMP安装PHP有区别,需要开启php-fpm服务。

3.1 准备PHP的包和用户

[root@host ~]# cd /usr/local/src/
[root@host src]# wget http://cn2.php.net/distributions/php-5.6.30.tar.gz   //下载php二进制包
[root@host src]# tar zxvf php-5.6.30.tar.gz   //解压缩
[root@host  src]# useradd -s /sbin/nologin php-fpm   //创建专门账号用来运行php-fpm服务,因为在LNMP环境中,PHP是以一种服务的形式独立存在的

3.2 卸载之前编译安装的PHP(如果之前有安装的话)

[root@host ~]# cd /usr/local/src
[root@host src]# ls
[root@host src]# cd php-5.6.30
[root@host php-5.6.30]# ls
[root@host php-5.6.30]# make clean

3.3 安装PHP

[root@host php-5.6.30]# cd php-5.6.30
[root@host php-5.6.30]# ./configure --prefix=/usr/local/php-fpm --with-config-file-path=/usr/local/php-fpm/etc --enable-fpm --with-fpm-user=php-fpm --with-fpm-group=php-fpm --with-mysql=/usr/local/mysql --with-mysqli=/usr/local/mysql/bin/mysql_config --with-pdo-mysql=/usr/local/mysql --with-mysql-sock=/tmp/mysql.sock --with-libxml-dir --with-gd --with-jpeg-dir --with-png-dir --with-freetype-dir --with-iconv-dir --with-zlib-dir --with-mcrypt --enable-soap --enable-gd-native-ttf --enable-ftp --enable-mbstring --enable-exif --with-pear --with-curl  --with-openssl   //初始化

3.4 编译过程中的出错排查

错误1:

onfigure: error: xml2-config not found. Please check your libxml2 installation.

解决办法1:

[root@host php-5.6.30]# yum list |grep libxml2
libxml2.x86_64                          2.9.1-6.el7_2.3                @anaconda
libxml2.i686                            2.9.1-6.el7_2.3                base    
libxml2-devel.i686                      2.9.1-6.el7_2.3                base    
libxml2-devel.x86_64                    2.9.1-6.el7_2.3                base    
libxml2-python.x86_64                  2.9.1-6.el7_2.3                base    
libxml2-static.i686                    2.9.1-6.el7_2.3                base    
libxml2-static.x86_64                  2.9.1-6.el7_2.3                base    

[root@host php-5.6.30]# yum install -y libxml2 libxml2-devel     //一般只需要安裝devel的庫文件就好了

错误2:

configure: error: Cannot find OpenSSL's <evp.h>

解决办法2:

[root@host php-5.6.30]# yum install -y openssl openssl-devel

错误3:

configure: error: Please reinstall the libcurl distribution -
    easy.h should be in <curl-dir>/include/curl/

解决办法3:

[root@host php-5.6.30]# yum install -y libcurl libcurl-devel

错误4:

configure: error: jpeglib.h not found.

解决办法4:

[root@host php-5.6.30]# yum install -y libjpeg libjpeg-turbo-devel 

错误5:

configure: error: png.h not found.

解决办法5:

[root@host php-5.6.30]# yum install -y libpng libpng-devel

错误6:

configure: error: freetype-config not found.

解决办法6:

[root@host php-5.6.30]# yum install -y freetype freetype-devel

错误7:

configure: error: mcrypt.h not found. Please reinstall libmcrypt.

解决办法7:

[root@host php-5.6.30]# yum install -y libmcrypt libmcrypt-devel

错误8:

configure: error: mcrypt.h not found. Please reinstall libmcrypt.
(centos源不能安装libmcrypt-devel,由于版权的原因没有自带mcrypt的包rpm -qa|grep limcrypt limcrypt-devel,此源为rethot社区版的源)

解决办法8:安装第三方yum源

wget http://www.atomicorp.com/installers/atomic
sh ./atomic

yum  install  php-mcrypt  libmcrypt  libmcrypt-devel

检测、编译和安装

[root@host php-5.6.30]# echo $?
0

[root@host php-5.6.30]# make 

[root@host php-5.6.30]# make install

3.5 配置PHP

添加配置文件

[root@host php-5.6.30]# cp php.ini-production /usr/local/php-fpm/etc/php.ini

配置文件编辑

[root@host php-5.6.30]# vi /usr/local/php/etc/php-fpm.conf   //写入如下内容

[global]
#定义全局参数
pid = /usr/local/php-fpm/var/run/php-fpm.pid
error_log = /usr/local/php-fpm/var/log/php-fpm.log
[www]
listen = /tmp/php-fcgi.sock
#监听地址,也可以写:listen = 127.0.0.1::9000,本地监听,也可以监听其他IP:port
#此处格式会影响配置Nginx和PHP结合时Nginx寻址PHP的路径
listen.mode = 666
#当监听的为socket文件时该部分才生效,用于指定.sock文件的权限
user = php-fpm
group = php-fpm
#定义php-fpm服务的用户
pm = dynamic
pm.max_children = 50
pm.start_servers = 20
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500
rlimit_files = 1024
#以上部分为进程相关信息

配置启动脚本

[root@host etc]# cd /usr/local/src/php-5.6.30  //进入源码目录下来

[root@host php-5.6.30]#  cp sapi/fpm/init.d.php-fpm /etc/init.d/php-fpm  //把启动脚本放到到系统配置

[root@host php-5.6.30]# chmod 755 /etc/init.d/php-fpm  //修改权限

[root@host php-5.6.30]# chkconfig --add php-fpm  //添加到开机启动项

[root@host php-5.6.30]# chkconfig php-fpm on  //设置开机启动

[root@host php-5.6.30]# service php-fpm start  //启动php-fpm服务
Starting php-fpm  done

[root@host php-5.6.30]# ps aux |grep php-fpm  //查看后台www的pool是否启动

4. Nginx介绍

Nginx是一款轻量级的Web 服务器/反向代理服务器及电子邮件(IMAP/POP3)代理服务器,并在一个BSD-like 协议下发行。其特点是占有内存少,并发能力强,事实上nginx的并发能力确实在同类型的网页服务器中表现较好,中国大陆使用nginx网站用户有:百度、京东、新浪、网易、腾讯、淘宝等。

  • Nginx官网 nginx.org,最新版1.13,最新稳定版1.12
  • Nginx应用场景:web服务、反向代理、负载均衡
  • Nginx著名分支,淘宝基于Nginx开发的Tengine,使用上和Nginx一致,服务名,配置文件名都一样,和Nginx的最大区别在于Tenging增加了一些定制化模块,在安全限速方面表现突出,另外它支持对js,css合并
  • Nginx核心+lua相关的组件和模块组成了一个支持lua的高性能web容器openresty。

1、Nginx优点 Nginx设计为一个主进程多个工作进程的工作模式,每个进程是单线程来处理多个连接,而且每个工作进程采用了非阻塞I/O来处理多个连接,从而减少了线程上下文切换,从而实现了公认的高性能、高并发;因此在生成环境中会通过把CPU绑定给Nginx工作进程从而提升其性能;另外因为单线程工作模式的特点,内存占用就非常少了。 Nginx更改配置重启速度非常快,可以毫秒级,而且支持不停止Nginx进行升级Nginx版本、动态重载Nginx配置。 Nginx模块也是非常多,功能也很强劲,不仅可以作为http负载均衡,Nginx发布1.9.0版本还支持TCP负载均衡,还可以很容易的实现内容缓存、web服务器、反向代理、访问控制等功能。

2、Lua的优点 Lua是一种轻量级、可嵌入式的脚本语言,这样可以非常容易的嵌入到其他语言中使用。另外Lua提供了协程并发,即以同步调用的方式进行异步执行,从而实现并发,比起回调机制的并发来说代码更容易编写和理解,排查问题也会容易。Lua还提供了闭包机制,函数可以作为First Class Value 进行参数传递,另外其实现了标记清除垃圾收集。 因为Lua的小巧轻量级,可以在Nginx中嵌入Lua VM,请求的时候创建一个VM,请求结束的时候回收VM。

3、什么是ngx_lua ngx_lua是Nginx的一个模块,将Lua嵌入到Nginx中,从而可以使用Lua来编写脚本,这样就可以使用Lua编写应用脚本,部署到Nginx中运行,即Nginx变成了一个Web容器;这样开发人员就可以使用Lua语言开发高性能Web应用了。 ngx_lua提供了与Nginx交互的很多的API,对于开发人员来说只需要学习这些API就可以进行功能开发,而对于开发web应用来说,如果接触过Servlet的话,其开发和Servlet类似,无外乎就是知道接收请求、参数解析、功能处理、返回响应这几步的API是什么样子的。

4、开发环境 我们可以使用OpenResty来搭建开发环境,OpenResty将Nginx核心、LuaJIT、许多有用的Lua库和Nginx第三方模块打包在一起;这样开发人员只需要安装OpenResty,不需要了解Nginx核心和写复杂的C/C++模块就可以,只需要使用Lua语言进行Web应用开发了。

LNMP下修改 WordPress 上传文件大小限制

摘要

这个设置对于不限流和服务器硬盘够大的网站来说还是很有用处的,特别是对于一些高清视频,放在第三方网站上引用的话经常会被添加”广告”的,通过上述的办法上传到自己服务器上的视频文件就不存在这个问题了,配合 CDN 的话,用户端访问播放也是毫无压力的。

在使用 WordPress 的时候,不知道大家有没有用到上传大容量文件需求,最近明月再给公司的网站上上传一些高清MP4 视频文件的时候就碰到这样的问题了, WordPress 默认限制可上传单个媒体文件的大小为50MB 的,对于MP4 视频文件来说这个50 MB 真的是属于”毛毛雨”的级别了,稍微达到”高清”级的MP4 视频10分钟以内的占用量都在100MB 以上了。

未分类

对于我们个人博客来说基本上是很少有这方面的需求的,但是对于企业公司网站还别说真的不保证啥时候会碰到的这个需求的。于是,只有求助于谷姐和度娘了,结果找到的资料依然是”乱”,基本上很多都是各说各的,并且大部分是针对 Apache 的。总之,很多搜索到的资料照着做的话都没有能成功上传的,最后没有办法只能是拼凑各个资料后来验证了,还好,最终让我给”拼凑”出在LNMP环境下的解决办法了。

这个解决办法其实很简单,就是通过修改LNMP里PHP的php.ini文件里的上传文件限制参数和Nginx里对应站点的配置文件里添加上传文件参数来实现的,也就是说只需要修改两个VPS/云服务器上的文件即可,今天明月就分享给大家,希望可以帮到有此需求的站长们。

修改LNMP环境下PHP的php.ini文件中:

upload_max_filesize= 300M //这个是文件上传大小限制


post_max_size=300M //这个是post请求大小限制

这两个参数,记得这两个参数没有在一起的,所以修改的时候一定要分别找到修改,然后保存退出。

然后再Nginx对应的站点配置文件里(也就是www.mydomain.com.conf这样的文件)里添加如下参数到对应位置,如下图所示:

未分类

其实就是告诉Nginx客户端上传文件的容量限制和超时标准,添加:

client_max_body_size 300m;


client_body_timeout 120;

这两个配置进去即可。

至此,重启一下LNMP生产环境即可生效了,这时候再次进入 WordPress 后台的”媒体”的添加里就可以看到,对应的上传文件大小限制已经成为300MB了,如下图:

未分类

其实,这个设置对于不限流和服务器硬盘够大的网站来说还是很有用处的,特别是对于一些高清视频,放在第三方网站上引用的话经常会被添加”广告”的,通过上述的办法上传到自己服务器上的视频文件就不存在这个问题了,配合 CDN 的话,用户端访问播放也是毫无压力的。

zabbix安装配置(LNMP环境)

1、配置参数

zabbix对PHP参数、PHP模块有特殊要求。
如下模块要特别留意加上

bcmath        --enable-bcmath
mbstring    --enable-mbstring
sockets        --enable-sockets
gd            --with-gd
libxml        --with-libxml-dir=/usr/local
xmlwriter    同上
xmlreader    同上
ctype        默认支持
session        默认支持
gettext        默认支持

以下是我PHP的编译配置参数(需要yum install libxml2-devel bzip2-devel libcurl-devel libjpeg-devel libpng-devel freetype-devel gd -y)

编译:

[root@M4 ~]# ./configure  --prefix=/usr/local/php56 
--with-config-file-path=/usr/local/php56/etc --with-bz2 --with-curl 
--enable-ftp --enable-sockets --disable-ipv6 --with-gd 
--with-jpeg-dir=/usr/local --with-png-dir=/usr/local 
--with-freetype-dir=/usr/local --enable-gd-jis-conv  
--with-iconv-dir=/usr/local --enable-mbstring --enable-calendar 
--with-gettext --with-libxml-dir=/usr/local --with-zlib 
--with-pdo-mysql=mysqlnd --with-mysqli=mysqlnd --with-mysqli=mysqlnd 
--enable-dom --enable-xml --enable-fpm --with-libdir=lib64 --enable-bcmath

安装:

[root@M4 ~]# make && make install

配置:

[root@M4 ~]# cp php.ini-development /usr/local/php56/etc/php.ini
[root@M4 ~]# ln -s /usr/local/php56/etc/php.ini /etc/php.ini
[root@M4 ~]# cp /usr/local/php56/etc/php-fpm.conf.default /usr/local/php56/etc/php-fpm.conf
[root@M4 ~]# vim /usr/local/php/etc/php-fpm.d/www.conf #编辑
user = zabbix #设置php-fpm运行账号为www
group = zabbix #设置php-fpm运行组为www
security.limit_extensions = .php .php3 .php4 .php5 .js .css .jpg .gif .png .jpeg .html .ico .bmp

设置 php-fpm开机启动

[root@M4 ~]# cp /usr/local/src/php-56/sapi/fpm/init.d.php-fpm /etc/rc.d/init.d/php-fpm

#拷贝php-fpm到启动目录

[root@M4 ~]# chmod +x /etc/rc.d/init.d/php-fpm #添加执行权限
[root@M4 ~]# chkconfig php-fpm on #设置开机启动
[root@M4 ~]# vi /usr/local/php/etc/php.ini #编辑配置文件
找到:disable_functions =
修改为:disable_functions = passthru,exec,system,chroot,scandir,chgrp,chown,
shell_exec,proc_open,proc_get_status,ini_alter,ini_alter,ini_restore,dl,
openlog,syslog,readlink,symlink,popepassthru,stream_socket_server,escapeshellcmd,
dll,popen,disk_free_space,checkdnsrr,checkdnsrr,getservbyname,
getservbyport,disk_total_space,posix_ctermid,posix_get_last_error,posix_getcwd,
posix_getegid,posix_geteuid,posix_getgid, posix_getgrgid,posix_getgrnam,posix_getgroups,
posix_getlogin,posix_getpgid,posix_getpgrp,posix_getpid, posix_getppid,posix_getpwnam,posix_getpwuid,
posix_getrlimit, posix_getsid,posix_getuid,posix_isatty, posix_kill,posix_mkfifo,posix_setegid,posix_seteuid,
posix_setgid, posix_setpgid,posix_setsid,posix_setuid,posix_strerror,posix_times,posix_ttyname,posix_uname
#列出PHP可以禁用的函数,如果某些程序需要用到这个函数,可以删除,取消禁用。
找到:;date.timezone =
修改为:date.timezone = PRC #设置时区
找到:expose_php = On
修改为:expose_php = Off #禁止显示php版本的信息
找到:short_open_tag = Off
修改为:short_open_tag = ON #支持php短标签
找到opcache.enable=0
修改为opcache.enable=1 #php支持opcode缓存
找到:;opcache.enable_cli=1 #php支持opcode缓存
修改为:opcache.enable_cli=0
post_max_size=16M
max_execution_time=300
max_input_time=300
always_populate_raw_post_data=off
在最后一行添加:zend_extension=opcache.so #开启opcode缓存功能
:wq! #保存退出

2、nginx编译安装

nginx版本1.12.2,以下我的安装编译参数

编译

[root@M4 ~]# ./configure --prefix=/web/soft/nginx/ --with-http_stub_status_module --with-http_ssl_module

安装:

[root@M4 ~]# make && make install

配置nginx支持php

[root@M4 ~]# vim /web/soft/nginx/conf/nginx.conf   
server {
        listen       8095;
        server_name  zabbix;
        location  / {
           root /web/soft/nginx/zabbix;
        }
       location ~ .php$ {
           root /web/soft/nginx/zabbix;
           fastcgi_pass 127.0.0.1:9000;
           fastcgi_index index.php;
           fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
           include fastcgi_params;
        }

    } 
[root@M4 ~]# /etc/init.d/nginx restart #重启nginx
[root@M4 ~]# /etc/init.d/php-fpm restart #重启php-fpm

3、zabbix服务端安装

下载安装zabbix
所有版本下载地址:http://www.zabbix.com/download.php
// 一定先安装依赖

[root@M4 ~]# yum install net-snmp-devel libxml2-devel libcurl-devel libevent-devel
[root@M4 ~]# tar xf zabbix-3.4.4.tar.gz

编译

[root@M4 ~]# ./configure --prefix=/web/data/zabbix-3.4.4/ --enable-server 
--enable-agent --with-mysql --with-net-snmp --with-libcurl --with-libxml2

安装

[root@M4 ~]# make && make install

在zabbix server一般充当两个角色:server、angent,所以上面的配置参数也同时加上了–enable-agent。
备注:请安装好MySQL,snmp,curl开发库。
创建用户
为了安全考虑zabbix只使用普通用户运行,假如你当前用户叫ttlsa,那么你运行他,他便使用ttlsa身份运行。但是如果你在root环境下运行zabbix,那么zabbix将会主动使用zabbix用户来运行。但是如果你的系统没有名叫zabbix的用户,你需要创建一个用户,如下:

[root@M4 ~]# groupadd zabbix
[root@M4 ~]# useradd -g zabbix zabbix

配置zabbix_server配置文件,zabbix源码目录下

[root@M4 ~]# mkdir /etc/zabbix
[root@M4 ~]# cp config/zabbix_server.conf /etc/zabbix/
[root@M4 ~]# vim /etc/zabbix/zabbix_server.conf
DBName=zabbix
DBUser=root
DBPassword=ttlsapwd
DBPort=3306

4、数据库安装配置

安装:数据库安装 http://yangxx.net/?p=154

初始化数据库

zabbix server与proxy需要数据库,angent不需要。尤其要注意的是proxy只需要导入一个sql文件,而server一共要导入3个sql文件。我当时在搭建proxy的时候导入了3个sql,导致出现报错。后来才发现proxy只需要导入一个表结构即可。
我假想你安装好了MySQL,用户名为root,密码为ttlsapwd

[root@M4 ~]# mysql -uroot -pttlsapwd
mysql> create database zabbix default charset utf8;
mysql> quit;
[root@M4 ~]# mysql -uroot -pttlsapwd zabbix < database/mysql/schema.sql

备注:创建数据库请别忘记加default charset utf8,有可能会导致你出现中文乱码问题

如果你仅仅是初始化proxy的数据库,那么够了。如果初始化server,那么接着导入下面两个sql

[root@M4 ~]# mysql -uroot -pttlsapwd zabbix < database/mysql/images.sql
[root@M4 ~]# mysql -uroot -ppttlsapwd zabbix < database/mysql/data.sql

5、登录web开始配置

192.168.30.6:8095

6、开启zabbix中文

原来zabbix默认把对中文的支持给关闭了,我们需要修改zabbix的php源文件. 修改站点根目录下include/locales.inc.php文件.

[root@M4 ~]# vim include/locales.inc.php
function getLocales() {
        return array(
                'en_GB' => array('name' => _('English (en_GB)'),        'display' => true),
                'en_US' => array('name' => _('English (en_US)'),        'display' => true),
                'bg_BG' => array('name' => _('Bulgarian (bg_BG)'),      'display' => true),
                'zh_CN' => array('name' => _('Chinese (zh_CN)'),        'display' => true),
                //原本这里为false,请改为true
                ...........代码省略掉........
        );
}

7、agent安装

监控主机

安装zabbix-agent

首先需要在被监控的主机上安装agent,可以下载预编译好的RPM进行安装,下载地址:http://www.zabbix.com/download
也可以源码安装,类似server的安装,只是一个地方有区别,就是配置的参数只有一个:

[root@M4 ~]# ./configure –prefix=/home/zabbix --enable-agent

配置agent

以RPM安装为例,安装后的agent配置文件位置:/etc/zabbix/zabbix_agentd.conf,主要需要修改下列2项:

Server=192.168.0.41
ServerActive=192.168.0.41:10051
Hostname=M4
#配置成主机名需要在server hosts文件中添加对应信息或者直接使用本机IP

修改完成后,重启zabbix-agent 服务。