Nginx 在CentOS下的编译安装

Eave 2015.11.08 12:13

一、获取相关开源程序

1.利用CentOS Linux系统自带的yum命令安装、升级所需的程序库:

LANG=C
yum -y install gcc gcc-c++ autoconf freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel e2fsprogs e2fsprogs-devel krb5 krb5-devel libidn libidn-devel openssl openssl-devel openldap openldap-devel nss_ldap openldap-clients openldap-servers patch libtool automake telnet cmake bison bind-utils jwhois setuptool ntsysv

2.下载适用CentOS程序源码包:

这里用OpenResty(也称为ngx_openresty)代替了标准的Nginx。它是一个全功能的 Web 应用服务器。它打包了标准的Nginx核心,很多的常用的第三方模块,以及它们的大多数依赖项。

下载安装包

http://luajit.org/download.html
http://www.pcre.org/
https://openresty.org/cn/download.html

二、安装Nginx所需的LuaJIT

wget "http://luajit.org/download/LuaJIT-2.0.5.tar.gz"
tar -zxf LuaJIT-2.0.5.tar.gz
cd LuaJIT-2.0.5
make && make install

三、安装Nginx所需的pcre库

wget "https://ftp.pcre.org/pub/pcre/pcre-8.45.tar.gz"
tar -zxf pcre-8.45.tar.gz

四、安装Nginx

1、编译安装Nginx

wget "https://openresty.org/download/openresty-1.15.8.3.tar.gz"
tar -zxf openresty-1.15.8.3.tar.gz
cd openresty-1.15.8.3
# openresty配置参数
./configure --user=www --group=www --prefix=/usr/local --with-luajit --with-stream --with-ipv6 --with-http_stub_status_module --with-http_ssl_module --with-http_sub_module --with-http_realip_module --with-http_v2_module --with-threads --with-debug --with-http_addition_module --with-http_gzip_static_module --with-pcre=../pcre-8.45 --http-client-body-temp-path=/var/cache/nginx/client_body --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp
# nginx配置参数
./configure --user=www --group=www --prefix=/usr/local/nginx --with-stream --with-ipv6 --with-http_stub_status_module --with-http_ssl_module --with-http_sub_module --with-http_realip_module --with-http_v2_module --with-threads --with-debug --with-http_addition_module --with-http_gzip_static_module --with-pcre=../pcre-8.45 --http-client-body-temp-path=/var/cache/nginx/client_body --http-proxy-temp-path=/var/cache/nginx/proxy_temp --http-fastcgi-temp-path=/var/cache/nginx/fastcgi_temp --http-uwsgi-temp-path=/var/cache/nginx/uwsgi_temp --http-scgi-temp-path=/var/cache/nginx/scgi_temp
gmake && gmake install

2、创建Nginx日志目录

mkdir -p /var/log/nginx
mkdir -p /var/cache/nginx
chown -R www:www /var/log/nginx
chown -R www:www /var/cache/nginx

3、创建Nginx配置文件

在/usr/local/nginx/conf/目录中创建nginx.conf文件

rm -f /usr/local/nginx/conf/nginx.conf
vim /usr/local/nginx/conf/nginx.conf

输入以下内容

user www www;
worker_processes  4;
worker_cpu_affinity 0001 0010 0100 1000;
worker_rlimit_nofile 10240;

pid         /usr/local/nginx/nginx.pid;
error_log   /var/log/nginx/error.log notice;

events
{
    use epoll;
    accept_mutex on;
    multi_accept on;
    worker_connections  1024;
}

# socket proxy
stream
{
    upstream socket
    {
        server 127.0.0.1:9501;
    }

    server
    {
        listen 1120;
        proxy_pass socket;
    }
}

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

    sendfile                             on;
    tcp_nopush                           on;

    keepalive_timeout                    65;

    # 去除 nginx 版本
    server_tokens                        off;
    # 去除 Nginx 的 X-Powered-By header
    fastcgi_hide_header                  X-Powered-By;
    # 不允许被 iframe 加载
    add_header                           X-Frame-Options     SAMEORIGIN;

    server_names_hash_bucket_size        128;
    client_header_buffer_size            32k;
    large_client_header_buffers          4          32k;
    client_max_body_size                 20m;
    client_body_buffer_size              2m;
    client_header_timeout                60;
    client_body_timeout                  60;
    send_timeout                         60;

    # 为打开文件指定缓存,默认是没有启用的,max 指定缓存数量,建议和打开文件数一致,inactive 是指经过多长时间文件没被请求后删除缓存
    open_file_cache                      max=10240 inactive=60s;
    # open_file_cache 指令中的inactive 参数时间内文件的最少使用次数,如果超过这个数字,文件描述符一直是在缓存中打开的
    open_file_cache_min_uses             1;

    fastcgi_intercept_errors             on;
    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_min_length 1k;
    gzip_buffers    4 16k;
    gzip_http_version 1.0;
    gzip_comp_level 6;
    gzip_types text/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml;
    gzip_vary on;

    # http_proxy 设置
    client_body_temp_path                /var/cache/nginx/client_body 3 2;
    proxy_connect_timeout                75;
    proxy_send_timeout                   75;
    proxy_read_timeout                   75;
    proxy_buffer_size                    4k;
    proxy_buffers                        4 32k;
    proxy_busy_buffers_size              64k;
    proxy_temp_file_write_size           64k;
    proxy_temp_path                      /var/cache/nginx/proxy_temp 1 2;

    # HTTP头部有下划线的,在Nginx上就可以正常获取到了
    underscores_in_headers               on;

    # 限制同一客户端ip地址的最大并发数
    limit_conn_zone $binary_remote_addr zone=one:10m;
    # 限制下载速度
    limit_rate                          100k;

    log_format access '$remote_addr - $remote_user [$time_local] "$request" "$uri" $status $body_bytes_sent $request_time $upstream_response_time "$http_referer" "$http_user_agent" $http_x_forwarded_for "$server_name" "$http_host" "$cookie_userid" "$http_cookie" "$request_body"';
    log_format api '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent $request_time $upstream_response_time "$http_user_agent" $http_x_forwarded_for "$server_name" "$http_host" "$http_x_uid" "$http_x_token" "$http_x_app_version" "$http_x_app_channel" "$request_body"';

    server
    {
        listen      80 default_server;
        listen      [::]:80; # IPv6
        server_name _;

        return 404;
    }

    server
    {
        listen       80;
        server_name  127.0.0.1;

        # 限制同一客户端ip地址的最大并发数为5
        limit_conn one 5;
        
        root   /var/www/vhosts/www;
        index  index.html index.htm;

        access_log  /var/log/nginx/access.log access;
        error_log   /var/log/nginx/error.log notice;

        charset utf-8;
        autoindex off;
        autoindex_exact_size off;
        autoindex_localtime on;

        # 允许跨域访问
        add_header Access-Control-Allow-Origin *;
        # add_header Access-Control-Allow-Origin "https://www.google.com,https://www.baidu.com";

        # 添加响应cookie
        add_header Set-Cookie 'cookiename=cookievalue;path=/';

        location ~* .*\.html$
        {
            rewrite ^/(.*)\.html$ /index.php?$1 last;
            break;
        }

        location /
        {
            # 页面内容替换
            sub_filter_once off;
            sub_filter  'hello' 'HELLO';

            if (!-e $request_filename)
            {
                rewrite ^/(.*)$ /index.php?$1 last;
                break;
            }
        }

        location /user/
        {
            try_files $uri $uri/ /user1/index.php?q=$uri&$args;
        }

        # 严格匹配 301 永久 302 临时
        location = /api/share
        {
            return 301 http://www.domian.com/game/share?$query_string;
        }

        location /login/callback
        {
            return http://www.domian.com$request_uri;
        }

        location ^~ /api/
        {
            rewrite /api/userinfo /api.php?s=/game/userinfo   last;
            rewrite /api/usermore /api.php?s=/game/usermore   last;
            rewrite /api/pay      /api.php?s=/game/pay        last;
        }

        # 对 /avatar 改变root目录
        location ^~ /avatar|avt
        {
            root /var/www/vhosts/avatar;
        }

        location /status
        {
            stub_status on;
            access_log off;
            allow 192.168.10.0/24;
            deny all;
        }

        # 过滤.git文件夹
        location ^~ /\.git
        {
            return 444;
        }

        # redirect server error pages to the static page /404.html /50x.html
        error_page  404               /404.html;
        error_page   500 502 503 504  /50x.html;

        location ~* /(50x|404).html
        {
            root   html;
        }

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        location ~* .*\.php?$
        {
            fastcgi_pass   phpfpm;
            fastcgi_index  index.php;
            include        fastcgi.conf;
        }

        location ~* .*\.(css|js|jpg|jpeg|gif|bmp|png|ico|ttf|ttc|woff|woff2|otf|svg|eot|swf|txt)$
        {
            expires      30d;
            access_log   off;
        }

        # 禁止访问敏感文件
        location ~* .*\.(ht|sh|sql|conf|env)$
        {
            deny  all;
        }
    }

    server
    {
        listen       80;
        server_name  www.domain.com

        set $root_dir "/var/www/vhosts/www.v1.domain.com";
        if ($cookie_userid = "112093")
        {
            set $root_dir "/var/www/vhosts/www.v2.domain.com";
        }
        root   $root_dir;
        index  index.html index.htm;

        access_log  /var/log/nginx/access.log  access;
        error_log   /var/log/nginx/error.log notice;
    }

    server
    {
        listen       80;
        server_name  websocket.domain.com;
        access_log  /var/log/nginx/api.domain.com.log  access;
        error_log   /var/log/nginx/api.domain.com.err  debug_http;

        location /
        {
            content_by_lua_file '/usr/local/nginx/conf/lua/websocket.lua';
        }

        location @websocket
        {
            proxy_pass http://127.0.0.1:9502;
            proxy_http_version       1.1;
            proxy_set_header         Upgrade               $http_upgrade;
            proxy_set_header         Connection            "upgrade";
        }

        location /websocket
        {
            proxy_pass http://127.0.0.1:9502;
            proxy_http_version       1.1;
            proxy_set_header         Upgrade               $http_upgrade;
            proxy_set_header         Connection            "upgrade";
        }
    }

    server
    {
        listen       80;
        server_name  www.domain.com

        set $group "v1";
        if ($cookie_userid = "112093")
        {
            set $group "v2";
        }

        location /
        {
            proxy_pass http://$group;
            proxy_set_header         Host                  $host;
            proxy_set_header         X-Real-IP             $remote_addr;
            proxy_set_header         X-Real-Port           $remote_port;
            proxy_set_header         X-Remote-Addr         $remote_addr;
            proxy_set_header         X-Forwarded-For       $proxy_add_x_forwarded_for;
        
            proxy_http_version      1.1;
            proxy_set_header        Connection             "";
        }
    }

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

        access_log   /var/log/nginx/www.domain.com.log  access;
        error_log    /var/log/nginx/error.log debug_http;

        charset utf-8;
        autoindex off;
        autoindex_exact_size off;
        autoindex_localtime on;

        location /
        {
            rewrite /(.+)\.((s|x)?htm(l)?|do|json)$ /$1 last;

            proxy_pass http://tomcat/www.domain.com/;
            proxy_set_header        Host                   127.0.0.1;
            proxy_set_header        X-Real-IP              $remote_addr;
            proxy_set_header        X-Real-Port            $remote_port;
            proxy_set_header        X-Remote-Addr          $remote_addr;
            proxy_set_header        X-Forwarded-For        $proxy_add_x_forwarded_for;
            proxy_set_header        From                   $http_host;
            
            proxy_cookie_path       /www.domain.com        /;
            proxy_set_header        Cookie                 $http_cookie;

            proxy_http_version      1.1;
            proxy_set_header        Connection             "";
        }

        location ^~ /backend1
        {
            proxy_pass http://tomcat;
            # /backend1/merchant -> /backend1/merchant
        }

        location ^~ /backend2
        {
            proxy_pass http://tomcat/;
            # /backend2/merchant -> //merchant
        }

        location ^~ /backend3/
        {
            proxy_pass http://tomcat;
            # /backend3/merchant -> /backend3/merchant
        }

        location ^~ /backend4/
        {
            proxy_pass http://tomcat/;
            # /backend4/merchant -> /merchant
        }

        # 文件不存在则转发到远程服务器
        location ^~ /book
        {
            try_files $uri @genpic;
        }

        location @genpic
        {
            proxy_pass http://images.domain.com;
            proxy_set_header         X-Real-IP             $remote_addr;
            proxy_set_header         X-Real-Port           $remote_port;
            proxy_set_header         X-Remote-Addr         $remote_addr;
            proxy_set_header         X-Forwarded-For       $proxy_add_x_forwarded_for;

            proxy_http_version       1.1;
            proxy_set_header         Connection            "";
        }

        location ~* .*\.(css|js|jpg|jpeg|gif|bmp|png|ico|ttf|ttc|woff|woff2|otf|svg|eot|swf|txt)$
        {
            root         /var/www/www.domain.com;
            expires      30d;
        }
    }

    # 设定负载均衡的服务器列表
    upstream phpfpm
    {
        # weigth参数表示权值,权值越高被分配到的几率越大
        # ip_hash;
        server 192.168.10.8:9000  max_fails=2 fail_timeout=30s;
        server 192.168.10.10:9000 backup;
    }

    upstream backend
    {
        least_conn;
        server 192.168.10.8  weight=10 max_fails=3 fail_timeout=20s;
        server 192.168.10.10 weight=2  max_fails=3 fail_timeout=20s;
    }

    upstream tomcat
    {
        least_conn;
        server 192.168.10.8:8080  weight=10 max_fails=3 fail_timeout=10s;
        server 192.168.10.10:8080 weight=2  max_fails=3 fail_timeout=10s;
    }

    include vhosts/*.conf;
}

5、启动Nginx

ln -s /usr/local/lib/libpcre.so.1 /usr/lib64/libpcre.so.1
ulimit -SHn 65535
/usr/local/nginx/sbin/nginx

三、配置开机自动启动Nginx

开机启动Nginx

vim /etc/rc.local

在末尾增加以下内容

ulimit -SHn 65535
/usr/local/nginx/sbin/nginx

四、日志切割脚本

1、shell脚本/var/www/scripts/cut_nginx_log.sh

#!/bin/bash

# The Nginx logs path
src_path="/var/log/nginx/"
dst_path="/var/log/nginx/"

files=`ls ${src_path} | grep ".log"`

mkdir -p ${dst_path}$(date -d "-1 day" +"%Y")/$(date -d "-1 day" +"%m")/

for i in $files
do
    if [ -f ${src_path}${i} ]
    then
        is=`echo $i | sed 's/\.log$//g'`
        mv ${src_path}${i} ${dst_path}$(date -d "-1 day" +"%Y")/$(date -d "-1 day" +"%m")/${is}-$(date -d "-1 day" +"%Y%m%d").log
    fi
done

# 删除两个月前的数据
rm -rf ${dst_path}$(date -d "-3 month" +"%Y")/$(date -d "-3 month" +"%m")

kill -USR1 `cat /usr/local/nginx/nginx.pid`

2、添加到Linux定时任务

# 定时切割Nginx日志
0 0 * * * /var/www/scripts/cut_nginx_log.sh > /dev/null 2>&1

附:Nginx错误日志级别说明

error_log file [debug|info|notice|warn|error|crit]|[{debug_core|debug_alloc|debug_mutex|debug_event|debug_http|debug_mail|debug_mysql}]

日志级别 = 错误日志级别 | 调试日志级别; 或者

日志级别 = 错误日志级别

错误日志的级别: emerg, alert, crit, error, warn, notic, info, debug,

调试日志的级别: debug_core, debug_alloc, debug_mutex, debug_event, debug_http, debug_mail, debug_mysql

error_log 指令的日志级别配置分为 错误日志级别和调试日志级别且错误日志只能设置一个级别且错误日志必须书写在调试日志级别的前面且调试日志可以设置多个级别