首页 > Nginx > Nginx 常用配置

Nginx 常用配置

不多说废话,直接上nginx.conf简洁版

#使用哪个用户启动nginx 
user  frankwong; 

#nginx 工作进程数,一般设置成CPU核数
worker_processes  4;

# [ debug | info | notice | warn | error | crit ]   错误日志的位置
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#nginx进程号保存文件
#pid        logs/nginx.pid;

events {
    #use [ kqueue | rtsig | epoll | /dev/poll | select | poll ] 使用epoll(linux2.6的高性能方式)
    use epoll;

    #每个worker最大连接数,受限于进程最大打开文件数目,参考ulimit -n
    worker_connections  1024;
}

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

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

    #日志文件格式
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
    #access_log  logs/access.log  main;

    #开启高效文件传输模式
    sendfile        on;
    
    #支持自定义带下划线的header
    underscores_in_headers on;
    
    #隐藏nginx 版本号
    server_tokens off;

    #防止网络阻塞
    #tcp_nopush     on;

    #长链接超时时间
    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    #上传文件大小限制
    client_max_body_size 20m
    #设定请求缓冲   
    client_header_buffer_size 1k;   
    large_client_header_buffers 4 4k; 

    server {
        #监听端口号
        listen       80;
        #配置基于名称的虚拟主机,通过它可以进行多域名转发
        server_name  localhost;

        #默认编码
        charset utf-8;

        #设定本虚拟主机的访问日志
        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }
        #错误页面
        error_page  404              /404.html;

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

1.开启gzip压缩 找到#gzip on这行,修改成如下内容即可

gzip  			on;
gzip_min_length 1k;//只压缩大于1K的文件
gzip_buffers 4 16k;
#gzip_http_version 1.0;//默认1.1
gzip_comp_level 2;//压缩级别,1-10,数字越大压缩的越好,时间也越长
gzip_types  text/plain application/javascript application/x-javascript text/javascript text/xml text/css;
gzip_vary on;//Squid等缓存服务有关,on的话会在Header里增加"Vary: Accept-Encoding"
gzip_disable "MSIE [1-6]."; //取消对IE6的支持

通过如下命令可以测试gzip是否生效

curl --header "Accept-Encoding: gzip,deflate,sdch" -I https://gitsea.com
HTTP/1.1 200 OK
Server: nginx
Date: Mon, 29 Sep 2014 05:24:45 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
Vary: Accept-Encoding
X-Powered-By: PHP/5.3.17
Vary: Cookie
X-Pingback: https://gitsea.com/xmlrpc.php
Content-Encoding: gzip

如果您看到Content-Encoding:gzip,说明生效

2.设置Nginx 监控

 location ~ ^/NginxStatus {
            stub_status on;//开启状态查看
            access_log off;//关闭日志
            allow   127.0.0.1;//设置仅能本机查看
            deny    all;
 }

生效之后输入http://127.0.0.1/NginxStatus 即可看到相关状态信息

Active connections: 328   
server accepts handled requests   
9309 8982 28890   
Reading: 1 Writing: 3 Waiting: 324

3.设置静态资源的缓存

 location ~ .(htm|html|gif|jpg|jpeg|png|ico|rar|css|js|zip|txt|flv|swf|doc|ppt|xls|pdf)$ {
            root  /opt/webapp/cache;//静态资源路径
            access_log off;
            expires 24h;//cache有效时间 这边设置成1天
 }

4.设置图片防盗链

location ~ .*.(gif|jpg|jpeg|png|bmp|swf)${
       expires      30d;
       valid_referers none blocked dropbag.sinaapp.com*;
       if ($invalid_referer) {
       rewrite ^/ https://gitsea.com/404.html;#return 404;
       }
}

5.平滑变更nginx配置 输入

/usr/local/nginx/sbin/nginx -t

如果结果显示

the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
the configuration file /usr/local/nginx/conf/nginx.conf was tested successfully

表示没有问题,则可以进行平滑重启,输入如下指令 nginx -s reload 其他常用指令如 nginx -s stop 停止nginx服务

6.日志切割

nginx的日志文件没有rotate功能。如果你不处理,日志文件将变得越来越大,所以需要写一个nginx日志切割脚本来自动切割日志文件。 第一步就是重命名日志文件,不用担心重命名后nginx找不到日志文件而丢失日志。在你未重新打开原名字的日志文件前,nginx还是会向你重命名的文件写日志,linux是靠文件描述符而不是文件名定位文件。 第二步向nginx主进程发送USR1信号。 nginx主进程接到信号后会从配置文件中读取日志文件名称,重新打开日志文件(以配置文件中的日志名称命名),并以工作进程的用户作为日志文件的所有者。 脚本文件nginx_log.sh如下

#nginx日志切割脚本
#!/bin/bash
#设置日志文件存放目录
logs_path="/usr/local/nginx/logs/"
#设置pid文件
pid_path="/usr/local/nginx/nginx.pid"

#重命名日志文件
mv ${logs_path}access.log ${logs_path}access_$(date -d "yesterday" +"%Y%m%d").log

#向nginx主进程发信号重新打开日志
kill -USR1 `cat ${pid_path}`

crontab 设置作业 0 0 * * * bash /usr/local/nginx/nginx_log.sh 这样就每天的0点0分把nginx日志重命名为日期格式,并重新生成今天的新日志文件。

7.反向代理和负载均衡

负责均衡需功能需要在编译nginx的时候把ngx_http_upstream_module模块编译进去 假设有3台tomcat服务器ip分别为192.168.1.101,192.168.1.102,192.168.0.103,我们需要用nginx对这3台tomcat服务器做负载均衡,使得在高访问量的情况下能够对req做分发。 配置如下

upstream tomcatserver{   
#weigth参数表示权值,默认为1,权值越高被分配到的几率越大,  
# max_fails=number 设定Nginx与服务器通信的尝试失败的次数。在fail_timeout参数定义的时间段内,如果失败的次数达到此值,Nginx就认为服务器不可用。在下一个fail_timeout时间段,服务器不会再被尝试。 失败的尝试次数默认是1。设为0就会停止统计尝试次数,认为服务器是一直可用的。 可以通过指令proxy_next_upstream、 fastcgi_next_upstream和 memcached_next_upstream来配置什么是失败的尝试。 默认配置时,http_404状态不被认为是失败的尝试。
#fail_timeout=time 设定统计失败尝试次数的时间段。在这段时间中,服务器失败次数达到指定的尝试次数,服务器就被认为不可用。服务器被认为不可用的时间段。默认情况下,该超时时间是10秒。
#backup 标记为备用服务器。当主服务器不可用以后,请求会被传给这些服务器。
#down 标记服务器永久不可用,可以跟ip_hash指令一起使用
server 192.168.1.101:8080  weight=5  max_fails=1 fail_timeout=30s;
server 192.168.1.102:8080  weight=1  max_fails=1 fail_timeout=30s;   
server 192.168.1.103:8080  weight=6  max_fails=1 fail_timeout=30s;   
}
#对 "/" 启用负载均衡   
location / {   
##当后端的服务器返回502、504、404,执行超时等错误,自动将请求转发到upstream负载均衡池中的另一台服务器,实现故障转移
proxy_next_upstream http_502 http_504 http_404 error timeout invalid_header;
proxy_pass http://tomcatserver;   
proxy_redirect          off;
proxy_set_header        Host $host;
proxy_set_header        X-Real-IP $remote_addr;//通过X-Forwarded-For获取用户真实IP
proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size    10m;//允许客户端请求的最大单文件字节数
client_body_buffer_size 128k;//缓冲区代理缓冲用户端请求的最大字节数
proxy_connect_timeout   300;//nginx跟后端服务器连接超时时间(代理连接超时)
proxy_send_timeout      300;//后端服务器数据回传时间(代理发送超时)
proxy_read_timeout      300;//连接成功后,后端服务器响应时间(代理接收超时)
proxy_buffer_size       4k;//设置代理服务器(nginx)保存用户头信息的缓冲区大小
proxy_buffers           4 32k;
proxy_busy_buffers_size 64k;//高负荷下缓冲大小
proxy_temp_file_write_size 64k;//设定缓存文件夹大小,大于这个值,将从upstream服务器传
}

8.域名跳转设置

server 
{ 
listen 80; 
server_name www.gitsea.com gitsea.com; 
if ($host != 'www.gitsea.com' ) { 
rewrite ^/(.*)$ http://www.gitsea.com/$1 permanent; 
}

9.https设置

server 
{  
listen 443 ssl;
listen       80;
#ssl on; //注释掉为了http和https共存
server_name  gitsea.com www.gitsea.com blog.gitsea.com;
index index.html index.htm index.php;
ssl_certificate ssl.crt;
ssl_certificate_key ssl.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;# omit SSLv3 because of POODLE (CVE-2014-3566)
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';
ssl_session_cache shared:ssl_session_cache:10m;
ssl_session_timeout 10m;
ssl_dhparam dhparam.pem;
}

设置http自动转发到https

server
        {
                listen       80;
                server_name  gitsea.com www.gitsea.com blog.gitsea.com;
                rewrite    ^ https://$server_name$request_uri? permanent;
}

 10.限制请求频率

编辑nginx.conf

http {

    geo $limited {
        default           1;
        121.41.105.67  0;//白名单,不限制访问频率
    }
    #map指令映射白名单的ip为空串
    map $limited $limit {
        1        $binary_remote_addr;
        0        "";
    } 
    #定义一个名为foo的limit_zone,大小10M内存来存储session,
    #  以$limit 为key
    #限制访问频率为每秒5次
    limit_req_zone $limit zone=foo:10m rate=5r/s;
....

编辑default.conf

server {
    listen       80;
    server_name  localhost;

    #charset koi8-r;
    #access_log  /var/log/nginx/log/host.access.log  main;

    location / {
    limit_req zone=foo burst=5 nodelay;
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

常用命令 -c </path/to/config> 为 Nginx 指定一个配置文件,来代替缺省的。 -t 不运行,而仅仅测试配置文件。nginx 将检查配置文件的语法的正确性,并尝试打开配置文件中所引用到的文件。 -v 显示 nginx 的版本。 -V 显示 nginx 的版本,编译器版本和配置参数。 问题 关于nginx并发数的计算,参加Nginx Wiki

worker_connections 
Syntax: worker_connections number 
Default: 
The worker_connections and worker_proceses from the main section allows you to calculate maxclients value: 
max_clients = worker_processes * worker_connections 
In a reverse proxy situation, max_clients becomes 
max_clients = worker_processes * worker_connections/4 
Since a browser opens 2 connections by default to a server ,and nginx uses the fds (file descriptors) from the same pool to connect to the upstream backend .

翻译 做http服务:浏览器只有1个连接 所以max_clients = worker_processes * worker_connections 做反向代理:从浏览器到nginx,然后从nginx到后端, 从后端到nginx,再由nginx到浏览器。max_clients = worker_processes * worker_connections/4

  1. huoqubing
    2014年6月24日16:47 | #1

    很屌的样子

  1. 本文目前尚无任何 trackbacks 和 pingbacks.
*