nginx autoindex开启目录浏览和索引

Nginx默认是不允许列出整个目录的。如需此功能,打开nginx.conf文件或你要启用目录浏览虚拟主机的配置文件,在server或location 段里添加上autoindex on;来启用目录流量,下面会分情况进行说明。

另外Nginx的目录流量有两个比较有用的参数,可以根据自己的需求添加:

autoindex_exact_size off;
默认为on,显示出文件的确切大小,单位是bytes。
改为off后,显示出文件的大概大小,单位是kB或者MB或者GB

autoindex_localtime on;
默认为off,显示的文件时间为GMT时间。
改为on后,显示的文件时间为文件的服务器时间

1、整个虚拟主机开启目录流量

在server段添加

location / {
    autoindex on;
    autoindex_localtime on; #之类的参数写这里
}

2、单独目录开启目录流量

2.1:直接二级目录开启目录流量

location /down/ {
    autoindex on;
}

2.2:虚拟目录开启目录流量

location /down/ {
    alias /home/wwwroot/lnmp/test/;
    autoindex on;
}

详细参照:http://nginx.org/en/docs/http/ngx_http_autoindex_module.html

需要注意root和alias的区别:

alias 设置的目录是准确的,可以理解为linux的 ln命令创建软连接,location就是软连接的名字。如上面2.2例子访问 http://域名/down/vpser.txt 是直接访问的/home/wwwroot/lnmp/test/下面的vpser.txt文件。

root 设置的目录是根目录,locatoin里所指定名称的目录,必须在root设定下的目录有相同名字的目录。如果将上面2.2例子里的alias改成root 访问 http://域名/down/vpser.txt 是直接访问的的/home/wwwroot/lnmp/test/down/ 目录下的vpser.txt文件。

需要注意的是alias目录必须要以 / 结尾且alias只能在location中使用。

如果想希望做出漂亮的目录列表,支持header,footer则可以安装三方插件:
http://wiki.nginx.org/NginxNgxFancyIndex

重启nginx,使其生效。

nginx auth_basic为目录添加密码保护

nginx可以为网站或目录甚至特定的文件设置密码认证。密码必须是crypt加密的。可以用apache的htpasswd来创建密码。

格式为:htpasswd -b -c site_pass username password

site_pass为密码文件。放在同nginx配置文件同一目录下,当然你也可以放在其它目录下,那在nginx的配置文件中就要写明绝对地址或相对当前目录的地址。

如果你输入htpasswd命令提示没有找到命令时,你需要安装httpd.如centos是yum install httpd

如果是为了给网站加上认证,可以直接将认证语句写在nginx的配置server段中。

如果是为了给目录加上认证,就需要写成目录形式了。同时,还要在目录中加上php的执行,否则php就会被下载而不执行了。

例如:基于整个网站的认证,auth_basic在php解释之前。

server {
    listen       80;
    server_name www.wkii.org akii.org;
    root  /www/akii;
    index index.html index.htm index.php;

    auth_basic "input you user name and  password";
    auth_basic_user_file /usr/local/nginx/conf/vhost/nginx_passwd;

    location ~ .php$ {
        fastcgi_pass  127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
    }
    location ~ /.ht {
         deny  all;
    }
    access_log /logs/akii.org_access.log main;
}

针对目录的认证,在一个单独的location中,并且在该location中嵌套一个解释php的location,否则php文件不会执行并且会被下载。auth_basic在嵌套的location之后。

server {
    listen       80;
    server_name www.wkii.org akii.org;
    root  /www/akii;
    index index.html index.htm index.php;

    location ~ ^/admin/.* {
        location ~ .php$ {
            fastcgi_pass  127.0.0.1:9000;
            fastcgi_index index.php;
            include fastcgi_params;
        }

        auth_basic "auth";
        auth_basic_user_file /usr/local/nginx/conf/vhost/auth/admin.pass;
    }

    location ~ .php$ {
        fastcgi_pass  127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
    }

    location ~ /.ht {
         deny  all;
    }
    access_log /logs/akii.org_access.log main;
}

这里有一个细节,就是location ~ ^/admin/.* {…} 保护admin目录下的所有文件。如果你只设了/admin/ 那么直接输入/admin/index.php还是可以访问并且运行的。 ^/admin/.* 意为保护该目录下所有文件。当然,只需要一次认证。并不会每次请求或每请求一个文件都要认证一下。

nginx指令add_before_body add_after_body向响应体前或后添加内容

ngx_http_addition_module在响应之前或者之后追加文本内容,比如想在站点底部追加一个js或者css,可以使用这个模块来实现,这个模块和淘宝开发的nginx footer模块有点类似,但是还是有不同. 这个模块需要依赖子请求,nginx footer依赖nginx写死的配置.

1. 安装nginx

# wget http://nginx.org/download/nginx-1.4.2.tar.gz
# tar -xzvf nginx-1.4.2.tar.gz
# cd nginx-1.4.2
#  --prefix=/usr/local/nginx-1.4.2 --with-http_stub_status_module --with-http_addition_module
# make
# make install

2. 指令(Directives)

语法: add_before_body uri;
默认值: —
配置段: http, server, location
发起一个子请求,请求给定的uri,并且将内容追加到主题响应的内容之前。

语法: add_after_body uri;
默认值: —
配置段: http, server, location
发起一个子请求,请求给定的uri,并且将内容追加到主题响应的内容之后。

syntax: addition_types mime-type …;
default: addition_types text/html;
context: http, server, location
这个指令在0.7.9开始支持,指定需要被追加内容的MIME类型,默认为“text/html”,如果制定为*,那么所有的

3. nginx配置addition

3.1 配置nginx.conf

server {
    listen       80;
    server_name  www.ttlsa.com;

    root /data/site/www.ttlsa.com;    

    location / {
        add_before_body /2013/10/header.html;
        add_after_body  /2013/10/footer.html;
    }
}

3.2 测试

以下三个文件,对应请求的主体文件和add_before_body、add_after_body对应的内容

# cat /data/site/test.ttlsa.com/2013/10/20131001_add.html 
<html>
<head>
<title>I am title</title>
</head>
<body>
ngx_http_addition_module
</body>
</html>

# cat /data/site/test.ttlsa.com/2013/10/header.html 
I am header!

# cat /data/site/test.ttlsa.com/2013/10/footer.html 
footer - ttlsa

看到20131001_add.html的顶部和底部分别嵌入了子请求header.html和footer的内容。

# curl test.ttlsa.com/2013/10/20131001_add.html           
I am header!
<html>
<head>
<title>I am title</title>
</head>
<body>
ngx_http_addition_module
</body>
</html>
footer - ttlsa

4. 结束语

addition模块与上节上节nginx sub替换响应内容模块应用场景有点相同,具体怎么使用,大家结合实际情况来使用.

CentOS 7安装Docker

先决条件

OS要求

需要64位的CentOS 7系统

卸载旧版本

Docker的旧版本称为docker或docker-engine。如果已经安装有,先卸载它及它的依赖

$ sudo yum remove docker 
                  docker-common 
                  container-selinux 
                  docker-selinux 
                  docker-engine

目前Docker CE(社区版本)称为docker-ce,Docker EE(企业版本)称为docker-ee。这里我们安装社区版本。

安装docker

配置仓库

1.安装yum-utils,提供了yum-config-manager工具:

$ sudo yum install -y yum-utils

2.使用如下命令配置一个稳定的仓库

$ sudo yum-config-manager 
    --add-repo 
    https://download.docker.com/linux/centos/docker-ce.repo

开始安装

1.更新yum软件包索引

$ sudo yum makecache fast

2.安装最新版本的docker

sudo yum install docker-ce

3.在生产系统,你应该安装一个指定版本的docker。列出所有可用版本

$ yum list docker-ce.x86_64  --showduplicates |sort -r

然后安装指定版本

sudo yum install docker-ce-<VERSION>

4.启动docker

$ sudo systemctl start docker

5.通过运行hello-world镜像来检测docker是否安装成功

$ sudo docker run hello-world

CentOS 7源码编译安装mysql 5.7

安装约定

mysql安装路径:/usr/local/mysql
mysql数据库路径: /data/mysql
mysql配置文件路径:/usr/local/mysql/my.cnf

卸载mariadb

# rpm -qa | grep mariadb
# rpm -e --nodeps mariadb-libs-5.5.37-1.el7_0.x86_64  Packet name is the last query that 

用户组和用户创建

创建用户组

groupadd mysql

创建用户

useradd -g mysql mysql -s / bin / false

下载源码软件包

Http://dev.mysql.com/downloads/mysql/5.7.html#downloads
Http://download.savannah.gnu.org/releases/libunwind/
Https://github.com/gperftools/gperftools/releases

# cd /usr/local/src/
# wget http://download.savannah.gnu.org/releases/libunwind/libunwind-1.1.tar.gz
# wget http://gperftools.googlecode.com/files/gperftools-2.5.tar.gz
# wget http://dev.mysql.com/get/Downloads/MySQL-5.7/mysql-5.7.x.tar.gz

安装libunwind

# tar zxvf libunwind-1.1.tar.gz
# cd libunwind-1.1
# ./configure
# make
# make install

安装gperftools

# cd ..
# tar zxvf gperftools-2.1.tar.gz
# cd gperftools-2.1
# ./configure
# make
# make install
# echo "/usr/local/lib" > /etc/ld.so.conf.d/usr_local_lib.conf
# ldconfig

安装mysql

# cd ..
# tar zxvf mysql-5.7.x.tar.gz
# cd mysql-5.7.x

在编译之前,使用如下命令来查看可用的编译参数描述

# cmake . -LH | more

如果编译出现错误,删除CMakeCache.txt重新编译

rm -rf CMakeCache.txt

开始编译:

# cmake -DCMAKE_INSTALL_PREFIX=/usr/local/mysql 
 -DMYSQL_DATADIR=/data/mysql 
 -DSYSCONFDIR=/etc 
 -DEXTRA_CHARSETS=all 
 -DDEFAULT_CHARSET=utf8 
 -DDEFAULT_COLLATION=utf8_general_ci 
 -DWITH_INNOBASE_STORAGE_ENGINE=1 
 -DENABLED_LOCAL_INFILE=1 
 -DMYSQL_UNIX_ADDR=/dev/shm/mysql.sock 
 -DMYSQL_TCP_PORT=3306 
 -DMYSQL_USER=mysql 
 -DWITH_DEBUG=0 
 -DDOWNLOAD_BOOST=1 
 -DWITH_BOOST=/usr/local/boost
# make
# make install
 ```

  change permission 
 ```
# chmod 755 /var/lib/mysql
# cd /usr/local/mysql
# chown -R mysql:mysql .

初始化mysql

/usr/local/mysql/bin/mysqld --initialize --basedir=/usr/local/mysql --datadir=/data/mysql --user=mysql --explicit_defaults_for_timestamp=1

创建一个mysql配置文件

# cp support-files/my-default.cnf /usr/local/mysql/my.cnf

安装并使用python requests发送http请求

Requests是一个Apache2 Licensed HTTP库,使用python编写。旨在设计成为易用的http请求库。意味着你不需要手动添加请求字符串到url,或者对POST数据进行表单编码。

安装Requests

有多种方法来安装requests库,如pip,easy_install和编译安装。
这里推荐pip,如执行:

pip install requests 

导入requests模块

要能够在python使用requests库,必须导入正确的模块。可以在脚本头部添加:

import requests 

发送请求

如获取一个网页的内容

r = request.get(‘https://github.com/timeline.json’)

获取响应状态码

发送请求后,准备往下对网页内容或url进一步处理时,最好先检查一下响应状态码。如下示例:

r = requests.get('https://github.com/timeline.json')
r.status_code
>>200

r.status_code == requests.codes.ok
>>> True

requests.codes['temporary_redirect']
>>> 307

requests.codes.teapot
>>> 418

requests.codes['o/']
>>> 200

获取内容

当web服务器返回响应体后,就可以收集你所需的内容了。

import requests
r = requests.get('https://github.com/timeline.json')
print r.text

# The Requests library also comes with a built-in JSON decoder,
# just in case you have to deal with JSON data

import requests
r = requests.get('https://github.com/timeline.json')
print r.json

查看响应头

通过使用python字典,可以访问和查看服务器的响应头。

r.headers
{
    'status': '200 OK',
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '148ms',
    'etag': '"e1ca502697e5c9317743dc078f67693f"',
    'content-type': 'application/json; charset=utf-8'
}

r.headers['Content-Type']
>>>'application/json; charset=utf-8'

r.headers.get('content-type')
>>>'application/json; charset=utf-8'

r.headers['X-Random']
>>>None

# Get the headers of a given URL
resp = requests.head("http://www.google.com")
print resp.status_code, resp.text, resp.headers

自定义请求头

如果想要添加自定义请求头到一个请求,必须传递一个字典到headers参数。

import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
headers = {'content-type': 'application/json'}

r = requests.post(url, data=json.dumps(payload), headers=headers)

发送一个POST请求

requests库也可以发送post请求,如下:

r = requests.post(http://httpbin.org/post)

当然也可以发送其它类型的请求,如 PUT, DELETE, HEAD和OPTIONS.

r = requests.put("http://httpbin.org/put")
r = requests.delete("http://httpbin.org/delete")
r = requests.head("http://httpbin.org/get")
r = requests.options("http://httpbin.org/get")

可以使用这些方法完成很多复杂的工作,如使用一个python脚本来创建一个GitHub repo。

import requests, json

github_url = "https://api.github.com/user/repos"
data = json.dumps({'name':'test', 'description':'some test repo'})
r = requests.post(github_url, data, auth=('user', '*****'))

print r.json

zabbix监控php-fpm状态

本文通过启用php-fpm的status页面,使用zabbix来定时获取此数据以达到监控php-fpm性能状态的目的。

安装

假设zabbix agent安装在了/zabbix-agent/目录

配置php-fpm

打开php-fpm的pool配置文件,删除pm.status=指令的注释:

pm.status_path = /php-fpm_status

如果你配置了多个pool,需要分别为它们配置不同的status_path。

配置nginx

把如下配置添加到nginx配置文件:

server {
    listen 10061;

    location /php-fpm_status {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

重启php-fpm和nginx后,尝试执行如下命令测试:

curl http://127.0.0.1:10061/php-fpm_status

添加User Parameters

创建/zabbix-agent/etc/zabbix_agentd.conf.d/php-fpm-params.conf文件,内容如下:

UserParameter=php-fpm[*],/usr/local/zabbix-agent-ops/bin/php-fpm-check.sh "$1" "$2"

创建/usr/local/zabbix-agent-ops/bin/php-fpm-check.sh,内容如下:

#!/bin/bash
##################################
# Zabbix monitoring script
#
# php-fpm:
#  - anything available via FPM status page
#
##################################
# Contact:
#  [email protected]
##################################
# ChangeLog:
#  20100922 VV  initial creation
##################################

# Zabbix requested parameter
ZBX_REQ_DATA="$1"
ZBX_REQ_DATA_URL="$2"

# Nginx defaults
NGINX_STATUS_DEFAULT_URL="http://localhost:80/php-fpm_status"
WGET_BIN="/usr/bin/wget"

#
# Error handling:
#  - need to be displayable in Zabbix (avoid NOT_SUPPORTED)
#  - items need to be of type "float" (allow negative + float)
#
ERROR_NO_ACCESS_FILE="-0.9900"
ERROR_NO_ACCESS="-0.9901"
ERROR_WRONG_PARAM="-0.9902"
ERROR_DATA="-0.9903" # either can not connect / bad host / bad port

# Handle host and port if non-default
if [ ! -z "$ZBX_REQ_DATA_URL" ]; then
  URL="$ZBX_REQ_DATA_URL"
else
  URL="$NGINX_STATUS_DEFAULT_URL"
fi

# save the nginx stats in a variable for future parsing
NGINX_STATS=$($WGET_BIN -q $URL -O - 2> /dev/null)

# error during retrieve
if [ $? -ne 0 -o -z "$NGINX_STATS" ]; then
  echo $ERROR_DATA
  exit 1
fi

# 
# Extract data from nginx stats
#
RESULT=$(echo "$NGINX_STATS" | awk 'match($0, "^'"$ZBX_REQ_DATA"':[[:space:]]+(.*)", a) { print a[1] }')
if [ $? -ne 0 -o -z "$RESULT" ]; then
    echo $ERROR_WRONG_PARAM
    exit 1
fi

echo $RESULT

exit 0

导入模板

导入php-fpm-template.xml模板,并链接到主机。根据需要设置{$PHP_FPM_STATUS_URL}宏。
php-fpm-template.xml模板内容:

<?xml version="1.0" encoding="UTF-8"?>
<zabbix_export>
    <version>2.0</version>
    <date>2013-03-26T04:12:09Z</date>
    <groups>
        <group>
            <name>Templates</name>
        </group>
    </groups>
    <templates>
        <template>
            <template>Template php-fpm</template>
            <name>Template php-fpm</name>
            <groups>
                <group>
                    <name>Templates</name>
                </group>
            </groups>
            <applications>
                <application>
                    <name>php-fpm</name>
                </application>
            </applications>
            <items>
                <item>
                    <name>$1</name>
                    <type>0</type>
                    <snmp_community/>
                    <multiplier>0</multiplier>
                    <snmp_oid/>
                    <key>php-fpm["total processes",{$PHP_FPM_STATUS_URL}]</key>
                    <delay>60</delay>
                    <history>90</history>
                    <trends>365</trends>
                    <status>0</status>
                    <value_type>3</value_type>
                    <allowed_hosts/>
                    <units/>
                    <delta>0</delta>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privpassphrase/>
                    <formula>1</formula>
                    <delay_flex/>
                    <params/>
                    <ipmi_sensor/>
                    <data_type>0</data_type>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <description/>
                    <inventory_link>0</inventory_link>
                    <applications>
                        <application>
                            <name>php-fpm</name>
                        </application>
                    </applications>
                    <valuemap/>
                </item>
                <item>
                    <name>$1</name>
                    <type>0</type>
                    <snmp_community/>
                    <multiplier>0</multiplier>
                    <snmp_oid/>
                    <key>php-fpm["listen queue",{$PHP_FPM_STATUS_URL}]</key>
                    <delay>60</delay>
                    <history>90</history>
                    <trends>365</trends>
                    <status>0</status>
                    <value_type>3</value_type>
                    <allowed_hosts/>
                    <units/>
                    <delta>0</delta>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privpassphrase/>
                    <formula>1</formula>
                    <delay_flex/>
                    <params/>
                    <ipmi_sensor/>
                    <data_type>0</data_type>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <description/>
                    <inventory_link>0</inventory_link>
                    <applications>
                        <application>
                            <name>php-fpm</name>
                        </application>
                    </applications>
                    <valuemap/>
                </item>
                <item>
                    <name>$1</name>
                    <type>0</type>
                    <snmp_community/>
                    <multiplier>0</multiplier>
                    <snmp_oid/>
                    <key>php-fpm["listen queue len",{$PHP_FPM_STATUS_URL}]</key>
                    <delay>60</delay>
                    <history>90</history>
                    <trends>365</trends>
                    <status>0</status>
                    <value_type>3</value_type>
                    <allowed_hosts/>
                    <units/>
                    <delta>0</delta>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privpassphrase/>
                    <formula>1</formula>
                    <delay_flex/>
                    <params/>
                    <ipmi_sensor/>
                    <data_type>0</data_type>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <description/>
                    <inventory_link>0</inventory_link>
                    <applications>
                        <application>
                            <name>php-fpm</name>
                        </application>
                    </applications>
                    <valuemap/>
                </item>
                <item>
                    <name>$1</name>
                    <type>0</type>
                    <snmp_community/>
                    <multiplier>0</multiplier>
                    <snmp_oid/>
                    <key>php-fpm["active processes",{$PHP_FPM_STATUS_URL}]</key>
                    <delay>60</delay>
                    <history>90</history>
                    <trends>365</trends>
                    <status>0</status>
                    <value_type>3</value_type>
                    <allowed_hosts/>
                    <units/>
                    <delta>0</delta>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privpassphrase/>
                    <formula>1</formula>
                    <delay_flex/>
                    <params/>
                    <ipmi_sensor/>
                    <data_type>0</data_type>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <description/>
                    <inventory_link>0</inventory_link>
                    <applications>
                        <application>
                            <name>php-fpm</name>
                        </application>
                    </applications>
                    <valuemap/>
                </item>
                <item>
                    <name>$1</name>
                    <type>0</type>
                    <snmp_community/>
                    <multiplier>0</multiplier>
                    <snmp_oid/>
                    <key>php-fpm["idle processes",{$PHP_FPM_STATUS_URL}]</key>
                    <delay>60</delay>
                    <history>90</history>
                    <trends>365</trends>
                    <status>0</status>
                    <value_type>3</value_type>
                    <allowed_hosts/>
                    <units/>
                    <delta>0</delta>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privpassphrase/>
                    <formula>1</formula>
                    <delay_flex/>
                    <params/>
                    <ipmi_sensor/>
                    <data_type>0</data_type>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <description/>
                    <inventory_link>0</inventory_link>
                    <applications>
                        <application>
                            <name>php-fpm</name>
                        </application>
                    </applications>
                    <valuemap/>
                </item>
                <item>
                    <name>$1/sec</name>
                    <type>0</type>
                    <snmp_community/>
                    <multiplier>0</multiplier>
                    <snmp_oid/>
                    <key>php-fpm["accepted conn",{$PHP_FPM_STATUS_URL}]</key>
                    <delay>60</delay>
                    <history>90</history>
                    <trends>365</trends>
                    <status>0</status>
                    <value_type>3</value_type>
                    <allowed_hosts/>
                    <units/>
                    <delta>1</delta>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privpassphrase/>
                    <formula>1</formula>
                    <delay_flex/>
                    <params/>
                    <ipmi_sensor/>
                    <data_type>0</data_type>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <description/>
                    <inventory_link>0</inventory_link>
                    <applications>
                        <application>
                            <name>php-fpm</name>
                        </application>
                    </applications>
                    <valuemap/>
                </item>
                <item>
                    <name>$1/sec</name>
                    <type>0</type>
                    <snmp_community/>
                    <multiplier>0</multiplier>
                    <snmp_oid/>
                    <key>php-fpm["slow requests",{$PHP_FPM_STATUS_URL}]</key>
                    <delay>60</delay>
                    <history>90</history>
                    <trends>365</trends>
                    <status>0</status>
                    <value_type>3</value_type>
                    <allowed_hosts/>
                    <units/>
                    <delta>1</delta>
                    <snmpv3_securityname/>
                    <snmpv3_securitylevel>0</snmpv3_securitylevel>
                    <snmpv3_authpassphrase/>
                    <snmpv3_privpassphrase/>
                    <formula>1</formula>
                    <delay_flex/>
                    <params/>
                    <ipmi_sensor/>
                    <data_type>0</data_type>
                    <authtype>0</authtype>
                    <username/>
                    <password/>
                    <publickey/>
                    <privatekey/>
                    <port/>
                    <description/>
                    <inventory_link>0</inventory_link>
                    <applications>
                        <application>
                            <name>php-fpm</name>
                        </application>
                    </applications>
                    <valuemap/>
                </item>
            </items>
            <discovery_rules/>
            <macros>
                <macro>
                    <macro>{$PHP_FPM_STATUS_URL}</macro>
                    <value>http://127.0.0.1:10061/php-fpm_status</value>
                </macro>
            </macros>
            <templates/>
            <screens/>
        </template>
    </templates>
    <graphs>
        <graph>
            <name>php-fpm Accepted Connections / sec</name>
            <width>900</width>
            <height>200</height>
            <yaxismin>0.0000</yaxismin>
            <yaxismax>100.0000</yaxismax>
            <show_work_period>1</show_work_period>
            <show_triggers>1</show_triggers>
            <type>0</type>
            <show_legend>1</show_legend>
            <show_3d>0</show_3d>
            <percent_left>0.0000</percent_left>
            <percent_right>0.0000</percent_right>
            <ymin_type_1>0</ymin_type_1>
            <ymax_type_1>0</ymax_type_1>
            <ymin_item_1>0</ymin_item_1>
            <ymax_item_1>0</ymax_item_1>
            <graph_items>
                <graph_item>
                    <sortorder>0</sortorder>
                    <drawtype>0</drawtype>
                    <color>C80000</color>
                    <yaxisside>0</yaxisside>
                    <calc_fnc>2</calc_fnc>
                    <type>0</type>
                    <item>
                        <host>Template php-fpm</host>
                        <key>php-fpm["accepted conn",{$PHP_FPM_STATUS_URL}]</key>
                    </item>
                </graph_item>
            </graph_items>
        </graph>
        <graph>
            <name>php-fpm Listen Queue</name>
            <width>900</width>
            <height>200</height>
            <yaxismin>0.0000</yaxismin>
            <yaxismax>100.0000</yaxismax>
            <show_work_period>1</show_work_period>
            <show_triggers>1</show_triggers>
            <type>0</type>
            <show_legend>1</show_legend>
            <show_3d>0</show_3d>
            <percent_left>0.0000</percent_left>
            <percent_right>0.0000</percent_right>
            <ymin_type_1>0</ymin_type_1>
            <ymax_type_1>0</ymax_type_1>
            <ymin_item_1>0</ymin_item_1>
            <ymax_item_1>0</ymax_item_1>
            <graph_items>
                <graph_item>
                    <sortorder>0</sortorder>
                    <drawtype>0</drawtype>
                    <color>EE0000</color>
                    <yaxisside>0</yaxisside>
                    <calc_fnc>2</calc_fnc>
                    <type>0</type>
                    <item>
                        <host>Template php-fpm</host>
                        <key>php-fpm["listen queue len",{$PHP_FPM_STATUS_URL}]</key>
                    </item>
                </graph_item>
                <graph_item>
                    <sortorder>1</sortorder>
                    <drawtype>0</drawtype>
                    <color>00EE00</color>
                    <yaxisside>0</yaxisside>
                    <calc_fnc>2</calc_fnc>
                    <type>0</type>
                    <item>
                        <host>Template php-fpm</host>
                        <key>php-fpm["listen queue",{$PHP_FPM_STATUS_URL}]</key>
                    </item>
                </graph_item>
            </graph_items>
        </graph>
        <graph>
            <name>php-fpm Processes</name>
            <width>900</width>
            <height>200</height>
            <yaxismin>0.0000</yaxismin>
            <yaxismax>100.0000</yaxismax>
            <show_work_period>1</show_work_period>
            <show_triggers>1</show_triggers>
            <type>0</type>
            <show_legend>1</show_legend>
            <show_3d>0</show_3d>
            <percent_left>0.0000</percent_left>
            <percent_right>0.0000</percent_right>
            <ymin_type_1>0</ymin_type_1>
            <ymax_type_1>0</ymax_type_1>
            <ymin_item_1>0</ymin_item_1>
            <ymax_item_1>0</ymax_item_1>
            <graph_items>
                <graph_item>
                    <sortorder>0</sortorder>
                    <drawtype>0</drawtype>
                    <color>C80000</color>
                    <yaxisside>0</yaxisside>
                    <calc_fnc>2</calc_fnc>
                    <type>0</type>
                    <item>
                        <host>Template php-fpm</host>
                        <key>php-fpm["total processes",{$PHP_FPM_STATUS_URL}]</key>
                    </item>
                </graph_item>
                <graph_item>
                    <sortorder>1</sortorder>
                    <drawtype>0</drawtype>
                    <color>00C800</color>
                    <yaxisside>0</yaxisside>
                    <calc_fnc>2</calc_fnc>
                    <type>0</type>
                    <item>
                        <host>Template php-fpm</host>
                        <key>php-fpm["active processes",{$PHP_FPM_STATUS_URL}]</key>
                    </item>
                </graph_item>
                <graph_item>
                    <sortorder>2</sortorder>
                    <drawtype>0</drawtype>
                    <color>0000C8</color>
                    <yaxisside>0</yaxisside>
                    <calc_fnc>2</calc_fnc>
                    <type>0</type>
                    <item>
                        <host>Template php-fpm</host>
                        <key>php-fpm["idle processes",{$PHP_FPM_STATUS_URL}]</key>
                    </item>
                </graph_item>
            </graph_items>
        </graph>
        <graph>
            <name>php-fpm Slow Requests / sec</name>
            <width>900</width>
            <height>200</height>
            <yaxismin>0.0000</yaxismin>
            <yaxismax>100.0000</yaxismax>
            <show_work_period>1</show_work_period>
            <show_triggers>1</show_triggers>
            <type>0</type>
            <show_legend>1</show_legend>
            <show_3d>0</show_3d>
            <percent_left>0.0000</percent_left>
            <percent_right>0.0000</percent_right>
            <ymin_type_1>0</ymin_type_1>
            <ymax_type_1>0</ymax_type_1>
            <ymin_item_1>0</ymin_item_1>
            <ymax_item_1>0</ymax_item_1>
            <graph_items>
                <graph_item>
                    <sortorder>0</sortorder>
                    <drawtype>0</drawtype>
                    <color>C80000</color>
                    <yaxisside>0</yaxisside>
                    <calc_fnc>2</calc_fnc>
                    <type>0</type>
                    <item>
                        <host>Template php-fpm</host>
                        <key>php-fpm["slow requests",{$PHP_FPM_STATUS_URL}]</key>
                    </item>
                </graph_item>
            </graph_items>
        </graph>
    </graphs>
</zabbix_export>

使用Nginx的error_page指令自定义404 50x错误页面

当nginx出现404和50x错误时,直接显示默认的nginx出错页面显得非常地不友好,我们可以自定义错误页面为用户显示友好的错误页面。这个用到了nginx的error_page指令。下面介绍在nginx配置自定义的404 50x错误页面。

创建你的自定义错误页面

我们把错误页面放到/usr/share/nginx/html目录,这个目录一般是在ubuntu通过apt安装时默认的nginx网站根目录。我们命名404错误页面为custom_404.html,500级别的错误页面称为custom_50x.html。执行如下命令创建错误页面:

echo "<h1 style='color:red'>Error 404: Not found :-(</h1>" | sudo tee /usr/share/nginx/html/custom_404.html
echo "<p>I have no idea where that file is, sorry.  Are you sure you typed in the correct URL?</p>" | sudo tee -a /usr/share/nginx/html/custom_404.html
echo "<h1>Oops! Something went wrong...</h1>" | sudo tee /usr/share/nginx/html/custom_50x.html
echo "<p>We seem to be having some technical difficulties. Hang tight.</p>" | sudo tee -a /usr/share/nginx/html/custom_50x.html

配置nginx使用你的错误页面

我们这里假设默认的nginx server配置在/etc/nginx/sites-enabled/default,打开此文件

vi /etc/nginx/sites-enabled/default

配置404错误页面

server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;

        . . .

        error_page 404 /custom_404.html;
        location = /custom_404.html {
                root /usr/share/nginx/html;
                internal;
        }
}

配置500级别错误页面

server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;

        . . .

        error_page 404 /custom_404.html;
        location = /custom_404.html {
                root /usr/share/nginx/html;
                internal;
        }

        error_page 500 502 503 504 /custom_50x.html;
        location = /custom_50x.html {
                root /usr/share/nginx/html;
                internal;
        }

        location /testing {
                fastcgi_pass unix:/does/not/exist;
        }
}

重启nginx并测试

检查配置文件语法

sudo nginx -t

重启nginx

sudo service nginx restart

测试404,在浏览器输入http://server_domain_or_IP/thiswillerror,将显示
Nginx
测试500,在浏览器输入http://server_domain_or_IP/testing,将显示
Nginx

使用virtualenv创建一个虚拟,多版本和独立的python开发环境

Virtualenv是一个用来创建虚拟的python开发环境的工具,可以使用它创建多个相互隔离的python环境而不需要担心影响到其它的python项目环境。

它可以为每个python项目创建独立的环境。它实际上没有单独的为每个python项目安装python副本,而是提供了一个方法来隔离各自的项目环境。

验证Virtualenv是否已经安装

执行如下命令来验证机器是否已经安装有Virtualenv:

virtualenv --version

如果看到输出版本号,如1.6.1,则表明已经安装有virtualenv。

安装virtualenv

有多种方法来安装virtualenv。
ubuntu和debian安装:

$ sudo apt-get install python-virtualenv

使用easy_install安装:

$ sudo easy_install virtualenv

使用pip安装

$ sudo pip install virtualenv

配置和使用Virtualenv

一旦安装好virtualenv,就可以开始创建自己的python环境了。
首先为隔离环境创建一个目录

mkdir ~/virtualenvironment

再为你的应用创建一个完整干净的python副本目录

virtualenv -p /usr/bin/python2.7 ~/virtualenvironment/my_new_app

其中-p为指定的python版本路径。
进到项目目录,激活你的虚拟环境

cd ~/virtualenvironment/my_new_app/bin

激活虚拟环境

source activate

现在注意到你已经进入虚拟环境了,现在你使用pip或easy_install安装的python包都会保存到my_new_app/lib/python2.7/site-packages目录
要退出虚拟环境,只需要键入”deactivate”

Virtualenv如何实现虚拟环境的

安装在你项目目录的python包不会影响到全局的python安装目录

Virtualenv不会创建每一个python文件来实现一个新的python环境

为了节省空间,使用了软链接来链接到全局环境的文件中并能加速虚拟环境创建

因此,必须已经有一个python环境安装在你的主机上

在你的Virtualenv安装一个包

执行如下命令:

pip install flask

Zabbix3监控Nginx性能状态

本文主要介绍使用zabbix来监控nginx的性能状态,包括当前活动的连接数,已经收到的请求数,已经处理的请求数等。

编辑nginx配置文件

vim /etc/nginx/nginx.conf
server {
        listen  8082;
        location /nginx_status {
                stub_status on;
                access_log   off;
        }
}

重启nginx

/etc/init.d/nginx restart

创建监控脚本

mkdir /etc/zabbix/scripts/
chown zabbix:zabbix -R /etc/zabbix/scripts/
chmod 750 /etc/zabbix/scripts/
vim /etc/zabbix/scripts/nginx-stats.sh
#!/bin/bash
##### OPTIONS VERIFICATION #####
if [[ -z "$1" || -z "$2" || -z "$3" ]]; then
  exit 1
fi
##### PARAMETERS #####
RESERVED="$1"
METRIC="$2"
STATSURL="$3"
CURL="/usr/bin/curl"
CACHE_TTL="55"
CACHE_FILE="/tmp/zabbix.nginx.`echo $STATSURL | md5sum | cut -d" " -f1`.cache"
EXEC_TIMEOUT="1"
NOW_TIME=`date '+%s'`
##### RUN #####
if [ -s "${CACHE_FILE}" ]; then
  CACHE_TIME=`stat -c"%Y" "${CACHE_FILE}"`
else
  CACHE_TIME=0
fi
DELTA_TIME=$((${NOW_TIME} - ${CACHE_TIME}))
#
if [ ${DELTA_TIME} -lt ${EXEC_TIMEOUT} ]; then
  sleep $((${EXEC_TIMEOUT} - ${DELTA_TIME}))
elif [ ${DELTA_TIME} -gt ${CACHE_TTL} ]; then
  echo "" >> "${CACHE_FILE}" # !!!
  DATACACHE=`${CURL} --insecure -s "${STATSURL}" 2>&1`
  echo "${DATACACHE}" > "${CACHE_FILE}" # !!!
  chmod 640 "${CACHE_FILE}"
fi
#
if [ "${METRIC}" = "active" ]; then
  cat "${CACHE_FILE}" | grep "Active connections" | cut -d':' -f2
fi
if [ "${METRIC}" = "accepts" ]; then
  cat "${CACHE_FILE}" | sed -n '3p' | cut -d" " -f2
fi
if [ "${METRIC}" = "handled" ]; then
  cat "${CACHE_FILE}" | sed -n '3p' | cut -d" " -f3
fi
if [ "${METRIC}" = "requests" ]; then
  cat "${CACHE_FILE}" | sed -n '3p' | cut -d" " -f4
fi
if [ "${METRIC}" = "reading" ]; then
  cat "${CACHE_FILE}" | grep "Reading" | cut -d':' -f2 | cut -d' ' -f2
fi
if [ "${METRIC}" = "writing" ]; then
  cat "${CACHE_FILE}" | grep "Writing" | cut -d':' -f3 | cut -d' ' -f2
fi
if [ "${METRIC}" = "waiting" ]; then
  cat "${CACHE_FILE}" | grep "Waiting" | cut -d':' -f4 | cut -d' ' -f2
fi
#
exit 0

增加执行权限

chown zabbix:zabbix /etc/zabbix/scripts/nginx-stats.sh
chmod 540 /etc/zabbix/scripts/nginx-stats.sh

测试脚本

sudo -u zabbix /etc/zabbix/scripts/nginx-stats.sh none active http://192.168.42.70:8082/nginx_status

到zabbix agent添加nginx监控

vim /etc/zabbix/zabbix_agentd.conf
UserParameter=nginx[*],/etc/zabbix/scripts/nginx-stats.sh "none" "$1" "$2"

重启zabbix agent

/etc/init.d/zabbix-agentd restart

测试监控

zabbix_get -s HOST -k "nginx[active,http://192.168.42.70:8082/nginx_status]"

添加监控项

在zabbix web中依次添加监控项,如添加active

nginx[active,http://192.168.42.70:8082/nginx_status]

完成后依次添加accepts,handled,requests,reading,writing,waiting的监控