Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1649008
  • 博文数量: 631
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 3920
  • 用 户 组: 普通用户
  • 注册时间: 2014-08-06 21:58
个人简介

博客是我工作的好帮手,遇到困难就来博客找资料

文章分类

全部博文(631)

文章存档

2022年(2)

2021年(4)

2020年(40)

2019年(4)

2018年(78)

2017年(213)

2016年(41)

2015年(183)

2014年(66)

我的朋友

分类: 系统运维

2017-03-11 22:20:40

user nobody;
#启动进程,通常设置成和cpu的数量相等
worker_processes  1;
  
#全局错误日志及PID文件
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
  
#pid        logs/nginx.pid;
  
#工作模式及连接数上限
events {
    #epoll是多路复用IO(I/O Multiplexing)中的一种方式,
    #仅用于linux2.6以上内核,可以大大提高nginx的性能
    use   epoll; 
  
    #单个后台worker process进程的最大并发链接数    
    worker_connections  1024;
  
    # 并发总数是 worker_processes 和 worker_connections 的乘积
    # 即 max_clients = worker_processes * worker_connections
    # 在设置了反向代理的情况下,max_clients = worker_processes * worker_connections / 4  为什么
    # 为什么上面反向代理要除以4,应该说是一个经验值
    # 根据以上条件,正常情况下的Nginx Server可以应付的最大连接数为:4 * 8000 = 32000
    # worker_connections 值的设置跟物理内存大小有关
    # 因为并发受IO约束,max_clients的值须小于系统可以打开的最大文件数
    # 而系统可以打开的最大文件数和内存大小成正比,一般1GB内存的机器上可以打开的文件数大约是10万左右
    # 我们来看看360M内存的VPS可以打开的文件句柄数是多少:
    # $ cat /proc/sys/fs/file-max
    # 输出 34336
    # 32000 < 34336,即并发连接总数小于系统可以打开的文件句柄总数,这样就在操作系统可以承受的范围之内
    # 所以,worker_connections 的值需根据 worker_processes 进程数目和系统可以打开的最大文件总数进行适当地进行设置
    # 使得并发总数小于操作系统可以打开的最大文件数目
    # 其实质也就是根据主机的物理CPU和内存进行配置
    # 当然,理论上的并发总数可能会和实际有所偏差,因为主机还有其他的工作进程需要消耗系统资源。
    # ulimit -SHn 65535
  
}
  
  
http {
    #设定mime类型,类型由mime.type文件定义
    include    mime.types;
    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 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,
    #对于普通应用,必须设为 on,
    #如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,
    #以平衡磁盘与网络I/O处理速度,降低系统的uptime.
    sendfile     on;
    #tcp_nopush     on;
  
    #连接超时时间
    #keepalive_timeout  0;
    keepalive_timeout  65;
    tcp_nodelay     on;
  
    #开启gzip压缩
    gzip  on;
    gzip_disable "MSIE [1-6].";
  
    #设定请求缓冲
    client_header_buffer_size    128k;
    large_client_header_buffers  4 128k;
  
  
    #设定虚拟主机配置
    server {
        #侦听80端口
        listen    80;
        #定义使用 访问
        server_name  ;
  
        #定义服务器的默认网站根目录位置
        root html;
  
        #设定本虚拟主机的访问日志
        access_log  logs/nginx.access.log  main;
  
        #默认请求
        location / {
             
            #定义首页索引文件的名称
            index index.php index.html index.htm;   
  
        }
  
        # 定义错误提示页面
        error_page   500 502 503 504 /50x.html;
        location = /50x.html {
        }
  
        #静态文件,nginx自己处理
        location ~ ^/(images|javascript|js|css|flash|media|static)/ {
             
            #过期30天,静态文件不怎么更新,过期可以设大一点,
            #如果频繁更新,则可以设置得小一点。
            expires 30d;
        }
  
        #PHP 脚本请求全部转发到 FastCGI处理. 使用FastCGI默认配置.
        location ~ .php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_index index.php;
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
  
        #禁止访问 .htxxx 文件
            location ~ /.ht {
            deny all;
        }
  
    }
}


2. 配置文件详解


#定义Nginx运行的用户和用户组,安装时建立的,如果用户不存在,就不能启动

user www www;


#启动进程,通常设置成和cpu的数量相等。相当于cpu个数,如果写多了,nginx会按给定的数据,往死里用

 8;


#错误日志定义类型,[ debug | info | notice | warn | error | crit ]

error_log /var/log/nginx/error.log info;


#主进程PID保存文件, 记录的是启动时占用进程的id号,是程序启动、停止、重启,判断是否在线的依据

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;


#工作进程最大允许连接数, 定义nginx进程最大连接数为6000;但是默认情况下Linux文件描述符为1024(通过 ulimit -a命令,查看open files的值),所以上面的文件描述符数量需要更改下(对应也需要更改open files的值,命令ulimit -SHn 65535,即比6000要大,否则为虚的并发量;想要开机永久生效,将ulimit -SHn 65535写入 /etc/rc.local文件中)

worker_connections 65535;

}


#整体环境配置

http

{

include mime.types; 

default_type application/octet-stream;  #设定mime类型,文件传送类型由mime.type文件定义


#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;用于异步传输(把来的请求先攒着,等达到一定量在再处理;并不是自己处理,而是交给fastcgi)大大提高了效率,也是nginx并发量大的原因,apache是同步传输


tcp_nopush on; #防止网络阻塞,这个是默认的,结果就是数据包不会马上传送出去,等到数据包最大时,一次性的传输出去,这样有助于解决网络堵塞。(只在sendfile on时有效)

tcp_nodelay on; #防止网络阻塞,禁用nagle算法,即不缓存数据


autoindex 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连接数的时候需要使用


server_tokens off; #隐藏nginx版本号(curl -I 172.16.115.160 可以查看,更加安全)

 

upstream huanglearn.com {

#upstream的负载均衡,weight是权重,可以根据机器配置定义权重。weigth参数表示权值,权值越高被分配到的几率越大。

server 192.168.80.21:80 weight=1;

server 192.168.80.22:80 weight=2;

server 192.168.80.23:80 weight=3;

}



#虚拟主机的配置

server

{

#监听端口

listen 80;


#域名可以有多个,用空格隔开

server_name huanglearn.com;

index index.html index.htm index.php;

root /data/www/huanglearn;



~表示匹配正则表达式,location用于curl,即在浏览器地址栏显示的内容


location ~ .*.(php|php5)?$

{

try_files $uri =404; #分析文件是否存在,如果不存在报404错误

fastcgi_pass 127.0.0.1:9000; #nginx以unix-domain-socket方式连接fastcgi(php)更快,适合大流量访问;另外一种 nginx连接fastcgi的方式是http方式:127.0.0.1:9000

fastcgi_index index.php; #默认网页文件

include fastcgi.conf; #fcgi.conf配置文件生效

}



#图片缓存时间设置

location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$

{

expires 10d;

}


#JS和CSS缓存时间设置

location ~ .*.(js|css)?$

{

expires 1h;

}


#log format #定义日志格式,自定义(默认没有)

log_format access '$remote_addr - $remote_user [$time_local] "$request" '

'$status $body_bytes_sent "$http_referer" '

'"$http_user_agent" $http_x_forwarded_for';


#定义本虚拟主机的访问日志

access_log /var/log/nginx/huanglearnaccess.log access;


#对 "/" 启用反向代理

location / {

proxy_pass

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服务器传

}


#开启status状态监测,本身用途不大,但是可以被服务器监控状态

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

}


#所有静态文件由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; 

}


location ~ .*.(js|css)?$

{ expires 1h;

 }

}

}




nginx

curl -I 127.0.0.1


(1)nginx虚拟主机

基于域名的虚拟主机

配置如下:

    server {

        listen       80;

        server_name  




        location / {

            root   /opt/html; 

            index  index.html index.htm;

        }



        error_page   500 502 503 504  /50x.html;

        location = /50x.html {

            root   html;

        }


    }


    server {

        listen       80;

        server_name  




        location / {

            root   /usr/html;

            index  index.html index.htm;

        }



        error_page   500 502 503 504  /50x.html;

        location = /50x.html {

            root   html;

        }


    }


访问URL:  



基于端口的虚拟主机


    server {

        listen       80;

        server_name  




        location / {

            root   /opt/html; 

            index  index.html index.htm;

        }



        error_page   500 502 503 504  /50x.html;

        location = /50x.html {

            root   html;

        }


    }


    server {

        listen       8080;

        server_name  




        location / {

            root   /usr/html;

            index  index.html index.htm;

        }



        error_page   500 502 503 504  /50x.html;

        location = /50x.html {

            root   html;

        }


    }


访问URL: :8080/   :80/


基于ip的虚拟主机

192.168.175.29

ifconfig eth3:1 192.168.175.28 netmask 255.255.255.0


server {

        listen       192.168.175.28:80;

        server_name  192.168.175.28;




        location / {

            root   /opt/html;

            index  index.html index.htm;

        }



        error_page   500 502 503 504  /50x.html;

        location = /50x.html {

            root   html;

        }


    }


server {

        listen       192.168.175.29:80;

        server_name  192.168.175.29;




        location / {

            root   /usr/html;

            index  index.html index.htm;

        }



        error_page   500 502 503 504  /50x.html;

        location = /50x.html {

            root   html;

        }


    }


访问URL: 192.168.175.28:80/   192.168.175.29:80/


(2)location使用


curl ''


    server {

        listen       80;

        server_name  




        location / {

            deny 192.168.175.1;

            allow 192.168.175.0/24;

            deny all;

            root   /opt/html;

            index  index.html index.htm;

        }



        error_page   500 502 503 504  /50x.html;

        location = /50x.html {

            root   html;

        }


    }


(3)ngx_http_auth_basic_module模块-权限验证

加密需要安装 yum install -y httpd 来加密

htpasswd  -c -b -m /usr/user test test


    server {

        listen       80;

        server_name  




        location / {

            auth_basic           "hello world";

            auth_basic_user_file /usr/user;

            root   /opt/html;

            index  index.html index.htm;

        }



        error_page   500 502 503 504  /50x.html;

        location = /50x.html {

            root   html;

        }


    }


(4)ngx_http_proxy_module 模块

例子: proxy_pass      


    server {

        listen       80;

        server_name  




        location / {

            proxy_pass       80;

            root   /opt/html;

            index  index.html index.htm;

        }



        error_page   500 502 503 504  /50x.html;

        location = /50x.html {

            root   html;

        }


    }


(5)ngx_http_upstream_module模块==反向代理

例子:

upstream backend {

    server backend1.example.com       weight=5;

    server backend2.example.com:8080;

    server unix:/tmp/backend3;


    server backup1.example.com:8080   backup;

    server backup2.example.com:8080   backup;

}


upstream nginx {

    server 192.168.175.29:8080;

    server 192.168.175.30:8080;

}


#####这里配置一个nginx和2个tomcat

具体配置如下:

upstream nginx {

       server 192.168.175.29:8080;

       server 192.168.175.30:8080;

    }


    server {

        listen       80;

        server_name  




        location / {

            proxy_pass      

            root   /opt/html;

            index  index.html index.htm;

        }



        error_page   500 502 503 504  /50x.html;

        location = /50x.html {

            root   html;

        }


    }


(6)tengine健康检查模块模块

例子:

http {

    upstream cluster1 {

        # simple round-robin

        server 192.168.0.1:80;

        server 192.168.0.2:80;

        check interval=3000 rise=2 fall=5 timeout=1000 type=http;

        check_http_send "HEAD / HTTP/1.0\r\n\r\n";

        check_http_expect_alive http_2xx http_3xx;

    }

    upstream cluster2 {

        # simple round-robin

        server 192.168.0.3:80;

        server 192.168.0.4:80;

        check interval=3000 rise=2 fall=5 timeout=1000 type=http;

        check_keepalive_requests 100;

        check_http_send "HEAD / HTTP/1.1\r\nConnection: keep-alive\r\n\r\n";

        check_http_expect_alive http_2xx http_3xx;

    }

    server {

        listen 80;

        location /1 {

            proxy_pass

        }

        location /2 {

            proxy_pass

        }

        location /status {

            check_status;

            access_log   off;

            allow SOME.IP.ADD.RESS;

            deny all;

        }

    }

}


配置如下:

upstream nginx {

       server 192.168.175.29:8080;

       server 192.168.175.30:8080;

        check interval=3000 rise=2 fall=5 timeout=1000 type=http;

        check_http_send "HEAD / HTTP/1.0\r\n\r\n";

        check_http_expect_alive http_2xx http_3xx;

    }


server {

        listen       80;

        server_name  




        location / {

            proxy_pass      

            root   /opt/html;

            index  index.html index.htm;

        }


        location /status {

            check_status;

        }


        error_page   500 502 503 504  /50x.html;

        location = /50x.html {

            root   html;

        }


    }


访问如下路径 /status


(7)利用memcache解决session一致性(session共享)


yum install -y memcached

servcie memcache start

telnet localhost 11211


[root@node1 apache-tomcat-7.0.61]# telnet localhost 11211

Trying ::1...

Connected to localhost.

Escape character is '^]'.

set abc 0 0 5

12345

STORED


(8)tegine session一致性


(9)nginx + keepalive 高可用






#定义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。


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连接数的时候需要使用



 limit_req_zone $binary_remote_addr zone=allips:10m rate=10r/m; #同一时间IP访问限制 防止DDOS攻击


 limit_conn_zone $binary_remote_addr zone=limitConn:10m;  #限制并发连接数



upstream blog.ha97.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;

}


#虚拟主机的配置


server

{

#监听端口


listen 80;


#域名可以有多个,用空格隔开


server_name ha97.com;

index index.html index.htm index.php;

root /data/www/ha97;


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

#定义本虚拟主机的访问日志

access_log /var/log/nginx/ha97access.log access;


#对 "/" 启用反向代理

location / {

proxy_pass

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

}

#所有静态文件由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; }

location ~ .*.(js|css)?$

{ expires 1h; }

}

}



nginx 负载均衡proxy 配置



在http模块 加入


upstream fuzai{

server 服务器ip;      #有端口的话 ip:端口 默认80端口可以不写

}



在server 模块需要负载的location加入


location / {

proxy_pass


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的rewrite


这个模块就是安装的时候用的pcre软件提供的


rewrite指定语法; rewrite regex replacement[flag]   应用位置 server、location 、if

该指令根据表达式来重定向URI,或者修改字符串。指令根据配置文件中的顺序来执行。注意重写表达式只对相对路径有效。如果你想配对主机名,你应该使用if语句,示例如下:


先说后面的flag 的几个说明吧:

1.last     相当于apache里面的[L]标记,表示rewrite。

2.break本条规则匹配完成后,终止匹配,不再匹配后面的规则。

3.redirect  返回302临时重定向,浏览器地址会显示跳转后的URL地址。

4.permanent  返回301永久重定向, 浏览器地址会显示跳转后的URL地址

例子: rewrite ^/(.*) permanent;      #rewrite是关键字  regex部分^/(.*) 这是一个正则表达式,表示匹配所以,匹配成功后跳转到后面的 replacement部分也就是这个域名  $1是引用前面()里面的内容简化写入的,permanent是301永久跳转,这是告诉搜索引擎的。



log_format 是定义日志格式的关键字  

main是标签 remote_addr 是记录访问客户端的地址  

remote_user 远程访问客户端的名称  

time_local是日期  

request 是http起始行的信息

status http的状态码 200 404 等  

body-bytes_set 是服务器发送给客户端的响应body字节数 


http_referer 记录这次访问是从那个链接访问过来的用于防盗链设置


http_user_agent 是记录浏览器的信息 比如是手机还是谷歌浏览器 360浏览器等  http_x_forwarded_for 当有代理时候设置这个记录客户端的真实地址用的

access_log 配置   语法: access_log path[format[buffer=size[flush=time]] [if=condition];     access_log path format gzip [=level] [buffer=size][flush=time][if=condition]  ;   access_log syslog:server=address[ paarmeter=value][format[if=condition]];

buffer=size 是存放访问日志的缓冲区大小,flush=time是日志多久刷新到硬盘的时间 ,gzip[level] 表示压缩级别 [if=condition] 表示其他条件 一般这些都不需要配置

access_log off 是关闭记录日志  可以应用到 http server location \if in locaton\limit_except中

例子: access_log logs/access_ main gzip buffer=32k flush=5s;





location的配置

nginx location语法


基本语法:location [=|~|~*|^~] /uri/ { … }


= 严格匹配。如果这个查询匹配,那么将停止搜索并立即处理此请求。


~ 为区分大小写匹配(可用正则表达式)


~* 为不区分大小写匹配(可用正则表达式)


!~和!~*分别为区分大小写不匹配及不区分大小写不匹配


^~ 如果把这个前缀用于一个常规字符串,那么告诉nginx 如果路径匹配那么不测试正则表达式。




Nginx 允许用户定义 Location block ,并指定一个匹配模式(pattern)匹配特定的 URI。除了简单的字符串(比如文件系统路径),还允许使用更为复杂的匹配模式(pattern)。

Location block 的基本语法形式是:


    location [=|~|~*|^~|@] pattern { ... }


[=|~|~*|^~|@] 被称作 location modifier ,这会定义 Nginx 如何去匹配其后的 pattern ,以及该 pattern 的最基本的属性(简单字符串或正则表达式)。


------- 关于 location modifier -------

1. =

这会完全匹配指定的 pattern ,且这里的 pattern 被限制成简单的字符串,也就是说这里不能使用正则表达式。

Example:

server {

    server_name website.com;

    location = /abcd {

    […]

    }

}


匹配情况:

           # 正好完全匹配

           # 如果运行 Nginx server 的系统本身对大小写不敏感,比如 Windows ,那么也匹配

    ?param1m2    # 忽略查询串参数(query string arguments),这里就是 /abcd 后面的 ?param1m2

    /    # 不匹配,因为末尾存在反斜杠(trailing slash),Nginx 不认为这种情况是完全匹配

    e    # 不匹配,因为不是完全匹配


2. (None)


可以不写 location modifier ,Nginx 仍然能去匹配 pattern 。这种情况下,匹配那些以指定的 patern 开头的 URI,注意这里的 URI 只能是普通字符串,不能使用正则表达式。

Example:

server {

    server_name website.com;

    location /abcd {

    […]

    }

}

匹配情况:

           # 正好完全匹配

           # 如果运行 Nginx server 的系统本身对大小写不敏感,比如 Windows ,那么也匹配

    ?param1m2    # 忽略查询串参数(query string arguments),这里就是 /abcd 后面的 ?param1m2

    /    # 末尾存在反斜杠(trailing slash)也属于匹配范围内

    e    # 仍然匹配,因为 URI 是以 pattern 开头的


3. ~

这个 location modifier 对大小写敏感,且 pattern 须是正则表达式

Example:

server {

    server_name website.com;

    location ~ ^/abcd$ {

    […]

    }

}

匹配情况:

           # 完全匹配

           # 不匹配,~ 对大小写是敏感的

    ?param1m2    # 忽略查询串参数(query string arguments),这里就是 /abcd 后面的 ?param1m2

    /    # 不匹配,因为末尾存在反斜杠(trailing slash),并不匹配正则表达式 ^/abcd$

    e    # 不匹配正则表达式 ^/abcd$


注意:对于一些对大小写不敏感的系统,比如 Windows ,~ 和 ~* 都是不起作用的,这主要是操作系统的原因。


4. ~*

与 ~ 类似,但这个 location modifier 不区分大小写,pattern 须是正则表达式

Example:

server {

    server_name website.com;

    location ~* ^/abcd$ {

    […]

    }

}

匹配情况:

           # 完全匹配

           # 匹配,这就是它不区分大小写的特性

    ?param1m2    # 忽略查询串参数(query string arguments),这里就是 /abcd 后面的 ?param1m2

    /    # 不匹配,因为末尾存在反斜杠(trailing slash),并不匹配正则表达式 ^/abcd$

    e    # 不匹配正则表达式 ^/abcd$


5. ^~

匹配情况类似 2. (None) 的情况,以指定匹配模式开头的 URI 被匹配,不同的是,一旦匹配成功,那么 Nginx 就停止去寻找其他的 Location 块进行匹配了(与 Location 匹配顺序有关)


6. @

用于定义一个 Location 块,且该块不能被外部 Client 所访问,只能被 Nginx 内部配置指令所访问,比如 try_files or error_page


------- 搜索顺序以及生效优先级 -------

因为可以定义多个 Location 块,每个 Location 块可以有各自的 pattern 。因此就需要明白(不管是 Nginx 还是你),当 Nginx 收到一个请求时,它是如何去匹配 URI 并找到合适的 Location 的。

要注意的是,写在配置文件中每个 Server 块中的 Location 块的次序是不重要的,Nginx 会按 location modifier 的优先级来依次用 URI 去匹配 pattern ,顺序如下:

    1. =

    2. (None)    如果 pattern 完全匹配 URI(不是只匹配 URI 的头部)

    3. ^~

    4. ~ 或 ~*

    5. (None)    pattern 匹配 URI 的头部


7.匹配案例

location  = / {

  # 精确匹配 / ,主机名后面不能带任何字符串

  [ configuration A ] 

}

location  / {

  # 因为所有的地址都以 / 开头,所以这条规则将匹配到所有请求

  # 但是正则和最长字符串会优先匹配

  [ configuration B ] 

}

location /documents/ {

  # 匹配任何以 /documents/ 开头的地址,匹配符合以后,还要继续往下搜索

  # 只有后面的正则表达式没有匹配到时,这一条才会采用这一条

  [ configuration C ] 

}

location ~ /documents/Abc {

  # 匹配任何以 /documents/ 开头的地址,匹配符合以后,还要继续往下搜索

  # 只有后面的正则表达式没有匹配到时,这一条才会采用这一条

  [ configuration CC ] 

}

location ^~ /images/ {

  # 匹配任何以 /images/ 开头的地址,匹配符合以后,停止往下搜索正则,采用这一条。

  [ configuration D ] 

}

location ~* \.(gif|jpg|jpeg)$ {

  # 匹配所有以 gif,jpg或jpeg 结尾的请求

  # 然而,所有请求 /images/ 下的图片会被 config D 处理,因为 ^~ 到达不了这一条正则

  [ configuration E ] 

}

location /images/ {

  # 字符匹配到 /images/,继续往下,会发现 ^~ 存在

  [ configuration F ] 

}

location /images/abc {

  # 最长字符匹配到 /images/abc,继续往下,会发现 ^~ 存在

  # F与G的放置顺序是没有关系的

  [ configuration G ] 

}

location ~ /images/abc/ {

  # 只有去掉 config D 才有效:先最长匹配 config G 开头的地址,继续往下搜索,匹配到这一条正则,采用

    [ configuration H ] 

}

location ~* /js/.*/\.js



顺序 no优先级:


(location =) > (location 完整路径) > (location ^~ 路径) > (location ~,~* 正则顺序) > (location 部分起始路径) > (/)

上面的匹配结果


按照上面的location写法,以下的匹配示例成立:


/ -> config A

精确完全匹配,即使/index.html也匹配不了

/downloads/download.html -> config B

匹配B以后,往下没有任何匹配,采用B

/images/1.gif -> configuration D

匹配到F,往下匹配到D,停止往下

/images/abc/def -> config D

最长匹配到G,往下匹配D,停止往下

你可以看到 任何以/images/开头的都会匹配到D并停止,FG写在这里是没有任何意义的,H是永远轮不到的,这里只是为了说明匹配顺序

/documents/document.html -> config C

匹配到C,往下没有任何匹配,采用C

/documents/1.jpg -> configuration E

匹配到C,往下正则匹配到E

/documents/Abc.jpg -> config CC

最长匹配到C,往下正则顺序匹配到CC,不会往下到E


8.实际使用建议

所以实际使用中,个人觉得至少有三个匹配规则定义,如下:

#直接匹配网站根,通过域名访问网站首页比较频繁,使用这个会加速处理,官网如是说。

#这里是直接转发给后端应用服务器了,也可以是一个静态首页

# 第一个必选规则

location = / {

    proxy_pass

}

# 第二个必选规则是处理静态文件请求,这是nginx作为http服务器的强项

# 有两种配置模式,目录匹配或后缀匹配,任选其一或搭配使用

location ^~ /static/ {

    root /webroot/static/;

}

location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {

    root /webroot/res/;

}

#第三个规则就是通用规则,用来转发动态请求到后端应用服务器

#非静态文件请求就默认是动态请求,自己根据实际把握

location / {

    proxy_pass

}


nginx配置https网站


前提:

    1、主机要先安装openssl


    2、编译安装nginx时,要加上--with-openssl和--with-http_ssl_module


1、生成自签字证书


[root@101 /]# openssl req -new -x509 -keyout  /root/ca.key  -out  /root/ca.crt


Generating a 2048 bit RSA private key

.............+++

...................................+++

writing new private key to '/root/ca.key'

Enter PEM pass phrase:        #输入密钥保护密码

Verifying - Enter PEM pass phrase:    #确认密码保护密码

-----

You are about to be asked to enter information that will be incorporated

into your certificate request.

What you are about to enter is what is called a Distinguished Name or a DN.

There are quite a few fields but you can leave some blank

For some fields there will be a default value,

If you enter '.', the field will be left blank.

-----

Country Name (2 letter code) [XX]:CN

State or Province Name (full name) []:guangzhou

Locality Name (eg, city) [Default City]:guangzhou

Organization Name (eg, company) [Default Company Ltd]:lzs

Organizational Unit Name (eg, section) []:it

Common Name (eg, your name or your server's hostname) []:101.lzs.com

Email Address []:root@lzs.com


2、修改配置文件openssl.cnf


vim /etc/pki/tls/openssl.cnf


[ ca ]

default_ca      = CA_default            # The default ca section

 

####################################################################

[ CA_default ]

 

dir             = /etc/pki/CA           #证书的根目录,要记住这个目录

certs           = $dir/certs            

crl_dir         = $dir/crl              

database        = $dir/index.txt       

#unique_subject = no                   

                                         

new_certs_dir   = $dir/newcerts        

 

certificate     = $dir/ca.crt       # 修改这里,表示签名时使用的证书

serial          = $dir/serial          

crlnumber       = $dir/crlnumber        

                                         

crl             = $dir/crl.pem         

private_key     = $dir/private/cakey.pem

RANDFILE        = $dir/private/.rand


3、复制证书到证书根目录/etc/pki/CA下,并在该目录下创建空文件index.txt和serial,并向serial输入”01“


cd /etc/pki/CA


cp /root/ca.crt .


touch index.txt


touch serial


echo "01" >serial


4、生成服务器RSA私钥/root/server.key


openssl genrsa -des3 -out /root/server.key 1024


5、为私钥去除口令


openssl rsa -in /root/server.key -out /root/server_nopwd.key


5、生成证书请求文件/root/server.csr


[root@101 /]# openssl req -new -key /root/server.key -out /root/server.csr


Enter pass phrase for /root/server.key:    #输入第4步生成的密钥的保护密码


You are about to be asked to enter information that will be incorporated

into your certificate request.

What you are about to enter is what is called a Distinguished Name or a DN.

There are quite a few fields but you can leave some blank

For some fields there will be a default value,

If you enter '.', the field will be left blank.

--------下面这部分应该和创建私有证书时填的一样------------------------

Country Name (2 letter code) [XX]:CN

State or Province Name (full name) []:guangzhou

Locality Name (eg, city) [Default City]:guangzhou

Organization Name (eg, company) [Default Company Ltd]:lzs

Organizational Unit Name (eg, section) []:it

Common Name (eg, your name or your server's hostname) []:101.lzs.com

----------------------------------------------------------------

Email Address []:root@lzs.com

 

Please enter the following 'extra' attributes

to be sent with your certificate request

A challenge password []:

An optional company name []:lzs


6、用私有证书给证书请求文件/root/server.csr签名


[root@101 CA]# openssl ca -in /root/server.csr -out /root/server.crt -cert /root/ca.crt -keyfile /root/ca.key -config /etc/pki/tls/openssl.cnf


Using configuration from /etc/pki/tls/openssl.cnf

Enter pass phrase for ca.key:

Check that the request matches the signature

Signature ok

Certificate Details:

        Serial Number: 1 (0x1)

        Validity

            Not Before: Aug 31 14:09:15 2016 GMT

            Not After : Aug 31 14:09:15 2017 GMT

        Subject:

            countryName               = CN

            stateOrProvinceName       = guangzhou

            organizationName          = lzs

            organizationalUnitName    = it

            commonName                = 101.lzs.com

            emailAddress              = root@lzs.com

        X509v3 extensions:

            X509v3 Basic Constraints: 

                CA:FALSE

            Netscape Comment: 

                OpenSSL Generated Certificate

            X509v3 Subject Key Identifier: 

                18:80:30:B7:C6:11:61:AE:F3:62:9D:D0:33:D9:97:CB:45:5A:31:91

            X509v3 Authority Key Identifier: 

                keyid:DA:99:4B:9B:29:A8:D8:14:54:FA:52:4B:1E:C3:E0:81:C6:A6:EF:42

 

Certificate is to be certified until Aug 31 14:09:15 2017 GMT (365 days)

Sign the certificate? [y/n]:yes

 

 

1 out of 1 certificate requests certified, commit? [y/n]y

Write out database with 1 new entries

Data Base Updated


7、编辑nginx配置文件/etc/nginx/nginx.conf


-------在配置文件的特定区域加入/修改下面内容

server {

        listen       443 ssl;        #设置监听的端口

        server_name  lzs;

        ssl     on;

        ssl_certificate /root/server.crt;

        ssl_certificate_key     /root/server_nopwd.key;


8、重启服务



阅读(1217) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~