Nginx详细配置到线上部署

2018-01-29 09:16:23 Linux 3114 0

最近看到有小伙伴在博客内搜索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,如果你在virtualBox下开发,也请设置为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 nginx.blog.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;
        #### backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。
        server 10.0.0.10:6666 down; 

        #### backup 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻
        server 10.0.0.11:7777 backup; 

        #### max_conns 限制到后端服务器的连接数
        server 10.0.0.11:8888 max_conns=200;

        #### `queue`   命令设置了当每个后端服务器都达到最大连接数后的队列大小
        #### `timeout` 参数指定了请求在队列中的保留时间。
        queue 10 timeout=30s;
    }

    #   虚拟主机的配置
    server
    {
        #   监听端口
        listen 80;
        #   域名可以有多个,用空格隔开
        server_name www.blog.com blog.com;
        index index.html index.htm index.php;
        root /data/www/blog;
        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 $request_time';
        #   定义本虚拟主机的访问日志
        access_log /var/log/nginx/ha97access.log access;
        #   对 "/" 启用反向代理

        location / {
            proxy_pass http://nginx.blog.com;
            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; 
        }

    }

}

通用配置示例

nginx.conf

##++++++++++++++++++++++++++ 全局配置 开始 +++++++++++++++++++++++++++++##

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

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

######## 进程文件
#pid  logs/nginx.pid;



events{
    ######## 参考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; 
    ######## epoll模型是Linux 2.6以上版本内核中的高性能网络I/O模型,如果跑在FreeBSD上面,就用kqueue模型。
    use epoll;

    ######## 单个进程最大连接数(最大连接数=连接数*进程数)
    worker_connections 1024;
}

##++++++++++++++++++++++++++ 全局配置 结束 +++++++++++++++++++++++++++++##


http { ##++++++++++++++++++++++++ http 开始 ++++++++++++++++++++++++++++##
    #### 隐藏 Nginx 的版本号
    server_tokens off; 

    #### 文件扩展名与文件类型映射表
    include mime.types;

    #### 默认文件类型
    default_type application/octet-stream;

    #### 默认编码
    charset utf-8;

    #### 开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。
    sendfile on; 

    #### 防止网络阻塞
    tcp_nopush  on;
    tcp_nodelay on;

    ####  开启目录列表访问,合适下载服务器,默认关闭。
    autoindex off;

    #### 保持连接时间
    keepalive_timeout  30s;

##########################################################################
## 负载均衡配置 upstream
##########################################################################

    upstream yth { 
        #### 每个请求按访问ip的hash结果分配,这样每个访客固定访问一个后端服务器,可以解决session的问题
        ip_hash;
        server 127.0.0.1:13888 weight=200;

        #### weight 默认为1.weight越大,负载的权重就越大
        #server 127.0.0.1:13888 weight=10;

        #### backup: 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻。
        #server 10.0.0.10:6666 down; 

        #### backup 其它所有的非backup机器down或者忙的时候,请求backup机器。所以这台机器压力会最轻
        #server 10.0.0.11:7777 backup; 

        #### max_conns 限制到后端服务器的连接数
        #server 10.0.0.11:8888 max_conns=200;

        #### `queue`   命令设置了当每个后端服务器都达到最大连接数后的队列大小
        #### `timeout` 参数指定了请求在队列中的保留时间。
        #queue 10 timeout=30s;
    }


##########################################################################
## 模块 fastcgi解析php
##########################################################################
    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
    gzip on; 

    #### 不压缩临界值,大于1K的才压缩,一般不用改
    gzip_min_length 1k;

    #### Buffer
    gzip_buffers 4 16k; 

    #### 压缩级别,1-10,数字越大压缩的越好
    gzip_comp_level 3;  

    #### 进行压缩的文件类型,但一般只对文本的压缩效果比较明显,不建议图片压缩
    gzip_types text/plain application/x-javascript text/css application/xml;

    #### 跟Squid等缓存服务有关,on的话会在Header里增加"Vary: Accept-Encoding"
    gzip_vary off;

    #### IE6对Gzip不怎么友好,不给它Gzip了
    gzip_disable "MSIE [1-6]\.";

    ### 单IP连接数限制,
            ### 50m为会话状态储存的空间
            ### rate=3r/s; 表示定义的请求频率为每秒6次请求
    limit_req_zone $binary_remote_addr zone=promote_req_limit:50m rate=6r/s;

    ### 格式化日志
    log_format access '$remote_addr - $remote_user [$time_local] "$request" '
        '$status $body_bytes_sent "$http_referer" '
        '"$http_user_agent" $http_x_forwarded_for $request_time';


##########################################################################
## 禁止以输入ip的方式访问 再在上个server后继续添加一段:
##########################################################################
    server{
        listen 80 default_server;
        server_name _;
        return 403;
    }
    include other_conf/*.conf; # 相对路径,相对于 nginx.conf 文件



} ##++++++++++++++++++++++++++ http 结束 ++++++++++++++++++++++++++++++##

fastcgi_params

它与 nginx.conf 同目录

fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  HTTPS              $https if_not_empty;

fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

mime.types

types {
    text/html                             html htm shtml;
    text/css                              css;
    text/xml                              xml;
    image/gif                             gif;
    image/jpeg                            jpeg jpg;
    application/javascript                js;
    application/atom+xml                  atom;
    application/rss+xml                   rss;

    text/mathml                           mml;
    text/plain                            txt;
    text/vnd.sun.j2me.app-descriptor      jad;
    text/vnd.wap.wml                      wml;
    text/x-component                      htc;

    image/png                             png;
    image/tiff                            tif tiff;
    image/vnd.wap.wbmp                    wbmp;
    image/x-icon                          ico;
    image/x-jng                           jng;
    image/x-ms-bmp                        bmp;
    image/svg+xml                         svg svgz;
    image/webp                            webp;

    application/font-woff                 woff;
    application/java-archive              jar war ear;
    application/json                      json;
    application/mac-binhex40              hqx;
    application/msword                    doc;
    application/pdf                       pdf;
    application/postscript                ps eps ai;
    application/rtf                       rtf;
    application/vnd.apple.mpegurl         m3u8;
    application/vnd.ms-excel              xls;
    application/vnd.ms-fontobject         eot;
    application/vnd.ms-powerpoint         ppt;
    application/vnd.wap.wmlc              wmlc;
    application/vnd.google-earth.kml+xml  kml;
    application/vnd.google-earth.kmz      kmz;
    application/x-7z-compressed           7z;
    application/x-cocoa                   cco;
    application/x-java-archive-diff       jardiff;
    application/x-java-jnlp-file          jnlp;
    application/x-makeself                run;
    application/x-perl                    pl pm;
    application/x-pilot                   prc pdb;
    application/x-rar-compressed          rar;
    application/x-redhat-package-manager  rpm;
    application/x-sea                     sea;
    application/x-shockwave-flash         swf;
    application/x-stuffit                 sit;
    application/x-tcl                     tcl tk;
    application/x-x509-ca-cert            der pem crt;
    application/x-xpinstall               xpi;
    application/xhtml+xml                 xhtml;
    application/xspf+xml                  xspf;
    application/zip                       zip;

    application/octet-stream              bin exe dll;
    application/octet-stream              deb;
    application/octet-stream              dmg;
    application/octet-stream              iso img;
    application/octet-stream              msi msp msm;

    application/vnd.openxmlformats-officedocument.wordprocessingml.document    docx;
    application/vnd.openxmlformats-officedocument.spreadsheetml.sheet          xlsx;
    application/vnd.openxmlformats-officedocument.presentationml.presentation  pptx;

    audio/midi                            mid midi kar;
    audio/mpeg                            mp3;
    audio/ogg                             ogg;
    audio/x-m4a                           m4a;
    audio/x-realaudio                     ra;

    video/3gpp                            3gpp 3gp;
    video/mp2t                            ts;
    video/mp4                             mp4;
    video/mpeg                            mpeg mpg;
    video/quicktime                       mov;
    video/webm                            webm;
    video/x-flv                           flv;
    video/x-m4v                           m4v;
    video/x-mng                           mng;
    video/x-ms-asf                        asx asf;
    video/x-ms-wmv                        wmv;
    video/x-msvideo                       avi;
}

配置单个web服务

首先 我们看 nginx.conf 第128行

include other_conf/*.conf;

表明我们要的单个配置文件要存在 nginx.conf 同一目录下的other_conf目录中,文件只要是以 .conf 结尾的文件都会被包含进去

示例 other_conf/blog.conf

##以下为单个server的常用配置信息
#--------------- 一级域名重定向到二级域名
server {
    listen 80;
    server_name hlzblog.top;
    return 302 http://www.hlzblog.top$request_uri;
}
server { ##++++++++++++++++++ Server 开始 ++++++++++++++++++++++++++##
    listen 80;
    server_name www.hlzblog.top hlzblog.top;

##########################################################################
## 基础配置
##########################################################################
    #### 项目地址
    root /data/www/blog/public;

    #### 默认自动访问目录下文件,读取不到,则从左往右
    index  index.html index.php;  

    #### 关闭 Nginx 版本显示,为了web安全
    server_tokens off;

##########################################################################
## 日志存储    通过crontab可定时移动文件为新名称,以切割日志
##########################################################################

    ####     全局错误日志定义类型,[ debug | info | notice | warn | error | crit ],路径为off则关闭
    error_log   logs/error.log info;
    ####     访问日志,路径为off则关闭
    access_log  logs/access.log;


##########################################################################
## 配置入口文件重写
##########################################################################
    location / {
        ##### 若访问路径的文件不存在,则重写URL转交给入口文件处理  
        if (!-e $request_filename) {  
           rewrite  ^/(.*)$  /index.php/$1  last;  
           break;  
        }
    }  

##########################################################################
## fastcgi配置
##########################################################################
    location ~ \.php {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_split_path_info ^(.+\.php)(.*)$; 
        fastcgi_param PATH_INFO $fastcgi_path_info; 
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

##########################################################################
## 配置缓存
##########################################################################
    #### 普通文件缓存
    location ~ \.(gif|jpg|jpeg|png|bmp)$ {
        access_log off; # 关闭访问日志记录
        expires 15d;
    }
    #### js、css缓存  因为js或者css有可能改动
    location ~ \.(js|css)$ {
        access_log off;
        expires 1h;
    }


##########################################################################
## 配置http状态 定向页面
##########################################################################
    error_page  404   /404.html;
    location = /404.html {
         root   html;
    }

    error_page  500 502 503 504  /50x.html;
    location = /50x.html {
         root   html;
    }



} ##+++++++++++++++++++++++++ Server 结束 ++++++++++++++++++++++++++++++##

注意该文件第43行

fastcgi_pass 127.0.0.1:9000;


表明了 php 的监听端口和IP信息,你需要手动去打开它,如果你只安装了php-cgi 那么

php-cgi -b 这里是ip:这里是port

即可打开,但是用 php-cgi 不稳定,还是用 php-fpm 去管理 php-cgi 比较好,php-fpm的具体配置本文不作重点,需要请自行搜索

同理,你要解析python 也可以用类似php的解析的方法去配置

配置反向代理服务

server {
    listen 80;
    server_name  puppeteer.hlzblog.top;

    #### 关闭版本显示   为了web安全
    server_tokens off;        
    location / {
        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:9001;

        add_header Access-Control-Allow-Origin *;
        add_header Access-Control-Allow-Methods "GET, POST";
        add_header Access-Control-Max-Age: 86400;
        # 对于附带身份凭证(Cookie)的请求,服务器不得设置 Access-Control-Allow-Origin 的值为"*"。
        ## add_header Access-Control-Allow-Credentials: true;
        add_header Access-Control-Allow-Headers 'Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
    }


    ## 配置http状态 定向页面

    error_page  404   /404.html;
    location = /404.html {
         root   html;
    }
    error_page  500 502 503 504  /50x.html;
    location = /50x.html {
         root   html;
    }
}

https配置示例

本地测试

如果想本地使用https测试,则需要生成自签证书

自签

本地生成自签证书

#!/bin/sh

# create self-signed server certificate:

read -p "Enter your domain [www.example.com]: " DOMAIN

echo "Create server key..."

openssl genrsa -des3 -out $DOMAIN.key 1024

echo "Create server certificate signing request..."

SUBJECT="/C=US/ST=Mars/L=iTranswarp/O=iTranswarp/OU=iTranswarp/CN=$DOMAIN"

openssl req -new -subj $SUBJECT -key $DOMAIN.key -out $DOMAIN.csr

echo "Remove password..."

mv $DOMAIN.key $DOMAIN.origin.key
openssl rsa -in $DOMAIN.origin.key -out $DOMAIN.key

echo "Sign SSL certificate..."

openssl x509 -req -days 3650 -in $DOMAIN.csr -signkey $DOMAIN.key -out $DOMAIN.crt

echo "TODO:"
echo "Copy $DOMAIN.crt to /etc/nginx/ssl/$DOMAIN.crt"
echo "Copy $DOMAIN.key to /etc/nginx/ssl/$DOMAIN.key"
echo "Add configuration in nginx:"
echo "server {"
echo "    ..."
echo "    listen 443 ssl;"
echo "    ssl_certificate     /etc/nginx/ssl/$DOMAIN.crt;"
echo "    ssl_certificate_key /etc/nginx/ssl/$DOMAIN.key;"
echo "}"

配置https

主要是需要将 80 端口请求转发到 443 端口

server {
    listen 80;
    server_name web.blog.com;
    return 301 https://web.blog.com:443$request_uri;
}    
server { ##++++++++++++++++++ Server 开始 ++++++++++++++++++++++++++##        
    server_name web.blog.com www.hlzblog.top;

    listen 443 ssl;
    ssl_certificate     /etc/nginx/ssl/web.blog.com.crt;
    ssl_certificate_key /etc/nginx/ssl/web.blog.com.key;

    ... # 其他配置,跟前文配置一样
}

配置完了,别忘记重启哟

注:若无特殊说明,文章均为云天河原创,请尊重作者劳动成果,转载前请一定要注明出处