10.4. Nginx系列

10.4.1. Nginx启动脚本

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

10.4.2. Nginx.conf配置

nginx.conf

user nobody nobody;
worker_processes 2;
error_log /usr/local/nginx/logs/nginx_error.log crit;
pid /usr/local/nginx/logs/nginx.pid;
worker_rlimit_nofile 51200;

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;
        }
    }
}

10.4.3. 默认虚拟主机

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

10.4.4. 用户认证

nginx_user_auth.conf

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

location  /
    {
        auth_basic              "Auth";
        auth_basic_user_file   /usr/local/nginx/conf/htpasswd;
}
}
yum install -y htttpd       //安装httpd
htpasswd -c /usr/local/nginx/conf/htpasswd hujianli     //创建hujianli用户
/usr/local/nginx/sbin/nginx -t
/usr/local/nginx/sbin/nginx -s reload

auth_basic_user_file 指定用户密码文件,前提是这个用户密码文件存在。
生成用户im文件的工具需要借助httpd的htpasswd。Nginx不自带这个工具。

mkdir /data/nginx/test.com
echo "test.com" > /data/nginx/test.com/index.html
curl -I -x 127.0.0.0.1:80 test.com

如果针对某个目录做用户密码认证,配置如下:

nginx_user_auth_admin.conf

location  /admin/
    {
        auth_basic              "Auth";
        auth_basic_user_file   /usr/local/nginx/conf/htpasswd;
}

10.4.5. 域名重定向

nginx_rewrite.conf

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

    if ($host != 'test.com' ) {
        rewrite  ^/(.*)$  http://test.com/$1  permanent;
    }

}

10.4.6. Nginx 的访问日志

使用access_log来指定日志的存储路径,最后面指定日志的格式名字。

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

    if ($host != 'test.com' ) {
        rewrite  ^/(.*)$  http://test.com/$1  permanent;
    }
    access_log /tmp/1.log combined_realip;
}

10.4.7. Nginx日志切割脚本

nginx_log_rotate.sh

#! /bin/bash
## 假设nginx的日志存放路径为/data/logs/
d=`date -d "-1 day" +%Y%m%d`
logdir="/data/logs"
nginx_pid="/usr/local/nginx/logs/nginx.pid"
cd $logdir
for log in `ls *.log`
do
    mv $log $log-$d
done
/bin/kill -HUP `cat $nginx_pid`


##add cron
#0 0 * * * /bin/bash /usr/local/sbin/nginx_log_rotate.sh

10.4.8. 配置静态文件不吉利日志并添加过期时间

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

    if ($host != 'test.com' ) {
        rewrite  ^/(.*)$  http://test.com/$1  permanent;
    }
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
    {
          expires      7d;
          access_log off;
    }
location ~ .*\.(js|css)$
    {
          expires      12h;
          access_log off;
    }
    access_log /tmp/1.log combined_realip;
}

10.4.9. Nginx防盗链

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 ;
    if ($invalid_referer) {
        return 403;
    }
    access_log off;
}

10.4.10. Nginx访问控制

nginx.conf 示例1

location /admin/
{
    allow 192.168.188.1;
    allow 127.0.0.1;
    deny all;
}

location /admin/
{
    deny 192.168.188.1;
    deny 127.0.0.1;
}

location ~ .*(abc|image)/.*\.php$
{
        deny all;
}

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

nginx.conf 示例2

#user  mwop mwop;

worker_processes  auto;

error_log  logs/error.log;

pid        logs/nginx.pid;

worker_rlimit_nofile 65535;

events {
    use epoll;
    worker_connections  10240;
}



http {
    include       mime.types;
    default_type  application/octet-stream;
    server_tokens off;

    gzip on;
    gzip_min_length 1k;
    gzip_buffers 16 8k;
    gzip_http_version 1.1;
    gzip_comp_level 2;
    gzip_types text/css text/xml application/javascript application/atom+xml application/rss+xml text/plain application/json application/x-javascript application/xml text/javascr
ipt;
    gzip_disable "MSIE [1-6]\.";
    gzip_vary on;
    client_max_body_size 100m;
    proxy_http_version 1.1;
    proxy_buffering on;
    proxy_buffer_size 4k;
    proxy_buffers 8 1M;
    proxy_busy_buffers_size 2M;
    rewrite_log on;


    log_format access  '$time_iso8601|$http_x_forwarded_for|$remote_addr|$http_host|$request_time|'
                       '$upstream_response_time|"$request"|$status|$body_bytes_sent|$request_length|'
                       '"$http_referer"|"$http_user_agent"|$upstream_addr|"$http_cookie"|';

    access_log  logs/access.log  access;

    sendfile        on;
    keepalive_timeout  120;

    # ----------------------------- 配置样例 -----------------------------------------
    limit_except GET {
        allow 192.168.1.0/24;       # 允许192.168.1.0/24范围的IP使用非GET的方法
        deny all;                   # 禁止其他所有来源IP的非GET请求
    }



# ------------------------------------- 反向代理 -----------------------------------------
    server {
        listen       0.0.0.0:2195;
        server_name  ng_fwjgj_prd_cmsk-dmz;

        location / {
            proxy_pass http://gateway.push.apple.com:2195;
            proxy_set_header Host $http_host;
        }

        #-------------------- 限速操作 ---------------------------
        location /flv/ {
            flv;
            limit_rate_after 500k;      #当传输速率到达500KB/s时进行限速
            limit_rate 50k;                 # 限速速率为50KB/s

        }
    }
    server {
        listen       0.0.0.0:8080;
        server_name  ng_fwjgj_prd_cmsk-dmz;

        location = /crm {
            rewrite ^(.*)$ https://$host/crm/;
        }

        location / {
            proxy_pass http://100.77.228.14:8080;
            proxy_set_header Host $http_host;
              proxy_connect_timeout 120;
              proxy_read_timeout 120;
              proxy_send_timeout 120;
              proxy_buffer_size 16k;
              proxy_buffers 4 64k;
              proxy_busy_buffers_size 128k;
              proxy_temp_file_write_size 128k;
              proxy_ssl_verify off;
              proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
              proxy_max_temp_file_size 0;
                    }
    }


}

10.4.11. Nginx解析PHP

省略

10.4.12. Nginx 代理

server
{
    listen 80;
    server_name ask.apelearn.com;

    location /
    {
        proxy_pass      http://121.201.9.155/;
        proxy_set_header Host   $host;
        proxy_set_header X-Real-IP      $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Nginx反向代理Zabbix服务器

nginx_zabbix.conf

server
{
    listen 80;
    server_name 192.168.188.128;

    location /
    {
        proxy_pass      http://192.168.188.128:8080/;
        proxy_set_header Host   $host;
        proxy_set_header X-Real-IP      $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

10.4.13. Nginx 配置ssl

server
{
    listen 443;
    server_name aming.com;
    index index.html index.php;
    root /data/nginx/aming.com;

    ssl on;
    ssl_certificate aminglinux.crt;
    ssl_certificate_key aminglinux.key;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;

    location ~ \.php$
    {
        include fastcgi_params;
        fastcgi_pass unix:/tmp/php-fcgi.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /data/nginx/aming.com$fastcgi_script_name;
    }
    access_log /tmp/1.log combined_realip;
}