设为首页 收藏本站
查看: 402|回复: 0

[经验分享] nginx 总结 原创-胡志广

[复制链接]

尚未签到

发表于 2016-12-25 11:31:37 | 显示全部楼层 |阅读模式

1.   Nginx无法启动解决方法


在查看到logs中报了如下错误时:
0.0.0.0:80 failed (10013: An attempt was made to access a socket in a way forbidden by its access permissions)
 
是因为80端口出现了冲突
 
 
 


2.   Weight ip_hash


在负载均衡均衡模块中upstream
Weight是可以把请求的链接优先访问该服务
Ip_hash会去将客户端转发到一个可用的服务器上
如果服务器不可用需要用down来标注
还有就是weightip_hash不能同时使用


3.   Nginx tomcat负载均衡和多域名同端口转发


Nginx进行http负载均衡的模块是upstream
Upstream可以进行多个配置,这样的话可以灵活的配置站点,但是注意的是upstream后面的名字最好是配置成为域名,因为upstream是进行http访问的,一般的解析没有问题,但是如果是ajax的解析就会通过访问upstream后面的名字来进行访问了,这里要注意。
 
修改配置文件:conf/nginx.conf
 
Upstreamserver的配置:
§  weight = NUMBER - 设置服务器权重,默认为1
§  max_fails = NUMBER - 在一定时间内(这个时间在fail_timeout参数中设置)检查这个服务器是否可用时产生的最多失败请求数,默认为1,将其设置为0可以关闭检查,这些错误在proxy_next_upstreamfastcgi_next_upstream404错误不会使max_fails增加)中定义。
§  fail_timeout = TIME - 在这个时间内产生了max_fails所设置大小的失败尝试连接请求后这个服务器可能不可用,同样它指定了服务器不可用的时间(在下一次尝试连接请求发起之前),默认为10秒,fail_timeout与前端响应时间没有直接关系,不过可以使用proxy_connect_timeoutproxy_read_timeout来控制。
§  down - 标记服务器处于离线状态,通常和ip_hash一起使用。
§  backup - (0.6.7或更高)如果所有的非备份服务器都宕机或繁忙,则使用本服务器(无法和ip_hash指令搭配使用)。
 
 
 
#需要进行负载均衡的站点
#其中server是其中负载均衡的一个节点www.aaa.com
upstream www.aaa.com { 
        server 192.168.0.1:8080 weight=1; 
server 192.168.0.2:8080 weight=2;
server 192.168.0.1:8081 weight=3;
        

 
#第二个网站的www.bbb.com的负载均衡的节点
upstream www.bbb.com { 
        server 192.168.1.1:8080 ; 
server 192.168.1.2:8080 ; 
server 192.168.1.3:8080 ; 
        ip_hash; 
 } 
 
#同一服务器转发2个不同域名进行负载均衡
#www.aaa.comserver
server
  {
    listen       80;
    server_name  www.aaa.com;
  
              location / { 
            index  index.html index.jsp; 
                     #这里的proxy_pass转发的是upstream的名字www.aaa.com
            proxy_pass  http://www.aaa.com; 
            proxy_set_header    X-Real-IP   $remote_addr; 
            client_max_body_size    100m; 
        } 
             
    #limit_conn   crawler  20;   
   
}
 
server
  {
    listen       80;
    server_name  www.bbb.com;
  
              location / { 
            index  index.html index.jsp; 
#这里的proxy_pass转发的是upstream的名字www.bbb.com
            proxy_pass  http://www.bbb.com; 
            proxy_set_header    X-Real-IP   $remote_addr; 
            client_max_body_size    100m; 
        } 
             
    #limit_conn   crawler  20;   
   
}
 
 


4.   linux安装nginx


先决条件
yum install gcc
yum install pcre pcre-devel
yum install zlib zlib-devel
yum install openssl openssl-devel
 
释放文件
tar –zxvf nginx.tar.gz
 
安装
./ configure –prefix=路径
make
make install
 
 
3)管理nginx服务
启动:
/usr/local/nginx/sbin/nginx
停止
/usr/local/nginx/sbin/nginx -s stop
重启
/usr/local/nginx/sbin/nginx  -s reload
查看状态
netstat -autlp| grep nginx
 
./configure     "--prefix=/export/servers/nginx"     "--sbin-path=/export/servers/nginx/sbin/nginx"     "--conf-path=/export/servers/nginx/conf/nginx.conf"     "--error-log-path=/export/servers/nginx/logs/error.log"     "--http-log-path=/export/servers/nginx/logs/access.log"     "--pid-path=/export/servers/nginx/var/nginx.pid"     "--lock-path=/export/servers/nginx/var/nginx.lock"     "--http-client-body-temp-path=/dev/shm//nginx_temp/client_body"     "--http-proxy-temp-path=/dev/shm/nginx_temp/proxy"     "--http-fastcgi-temp-path=/dev/shm/nginx_temp/fastcgi"     "--user=www"     "--group=www"     "--with-cpu-opt=pentium4F"     "--without-select_module"     "--without-poll_module"     "--with-http_realip_module"     "--with-http_sub_module"     "--with-http_gzip_static_module"     "--with-http_stub_status_module"     "--without-http_ssi_module"     "--without-http_userid_module"     "--without-http_geo_module"    "--without-http_map_module"     "--without-mail_pop3_module"     "--without-mail_imap_module"     "--without-mail_smtp_module"


5.   日志输出相应时间


"$request_time"';
log_format 后面添加上上面的参数即可
 
log_format main            '$remote_addr - $remote_user [$time_local] '
                                                       '"$request" $status $bytes_sent '
                                                       '"$http_referer" "$http_user_agent" '
                                                          '"$gzip_ratio"';
 


6.   设置cache-control


Http协议的cache-control的常见取值及其组合释义:
no-cache: 数据内容不能被缓存每次请求都重新访问服务器若有max-age, 则缓存期间不访问服务器.
no-store: 不仅不能缓存连暂存也不可以(临时文件夹中不能暂存该资源)
private(默认): 只能在浏览器中缓存只有在第一次请求的时候才访问服务器若有max-age, 则缓存期间不访问服务器.
public: 可以被任何缓存区缓存浏览器、服务器、代理服务器等
max-age: 相对过期时间即以秒为单位的缓存时间.
no-cache, private: 打开新窗口时候重新访问服务器若设置max-age, 则缓存期间不访问服务器.
private, 正数的max-age: 后退时候不会访问服务器
no-cache, 正数的max-age: 后退时会访问服务器
点击刷新无论如何都会访问服务器.
Expires:
设置以分钟为单位的绝对过期时间优先级比Cache-Control同时设置ExpiresCache-Control则后者生效.
Last-Modified:
该资源的最后修改时间在浏览器下一次请求资源时浏览器将先发送一个请求到服务器上并附上If-Unmodified-Since头来说明浏览器所缓存资源的最后修改时间如果服务器发现没有修改则直接返回304(Not Modified)回应信息给浏览器(内容很少), 如果服务器对比时间发现修改了则照常返回所请求的资源.
 
 
在网页中设置:
<meta http-equiv="Cache-Control" content="max-age=7200" />

<meta http-equiv="Expires" content="Mon, 20 Jul 2009 23:00:00 GMT" />
 
只对本网页有效
 
Nginx 设置:
相关页面设置Cache-Control头信息
 
if ($request_uri ~* "^/$|^/search/.+/|^/company/.+/") {
  add_header    Cache-Control  max-age=3600;
}
 
if ($request_uri ~* "^/search-suggest/|^/categories/") {
  add_header    Cache-Control  max-age=86400;
}
 
全局的就在location /下面配置即可
 
 


7.   静态压缩和动态压缩的区别


静态压缩:
静态压缩是之间就通过工具将文件通过压缩工具进行压缩,然后nginx只是做文件头设置即可;如:
文件为1.html,然后压缩后为1.html.gz
然后nginx的配置文件中配置:

location ~ \.gz$ {
add_header  Content-Encoding  gzip;
gzip off;//
这里的off是不进行动态压缩

}
因为之前我们的1.html已经压缩为1.html.gz了,所以这时我们只需要设置headergzip即可,不开启gzip动态压缩;
 
动态压缩:
动态压缩就是我们的文件之前不通过工具压缩,而通过nginx进行压缩,这样的为动态压缩,如:
 
#启动预压缩功能,对所有类型的文件都有效   
gzip_static on;   
  
#
找不到预压缩文件,进行动态压缩   
gzip on;    
gzip_min_length 1000;   
gzip_buffers 4 16k;   
gzip_comp_level 5;   
gzip_types text/plain application/x-javascript text/css application/xml;   
  
#gzip
公共配置   
gzip_http_version 1.1  
gzip_proxied expired no-cache no-store private auth;   

 
#纠结的配置   
#
对于ie有个bug,响应vary头后将不会缓存请求,每次都会重新发新的请求。所以,对于ie 1-6直接禁用gzip   
gzip_disable "MSIE [1-6]\.";   
#
开启Http Vary头,vary头主要提供给代理服务器使用,根据Vary头做不同的处理。例如,对于支持gzip的请求反向代理缓存服务器将返回gzip内容,不支持gzip的客户端返回原始内容。   
gzip_vary on;  

1.    gzip_static配置优先级高于gzip
2.    开启nginx_static后,对于任何文件都会先查找是否有对应的gz文件
3.    gzip_types设置对gzip_static无效
 
 


8.   nginx: [emerg] unknown directive "if(


nginx: [emerg] unknown directive "if($args" in /export/servers/nginx/conf/nginx.conf:90
这个错误是因为缺少 pcre 8.2的包
 
 
 


9.   安装nginx pcre问题解决方法


首先安装pcre需要安装openssl
然后pcre需要指定路径
 -with-pcre=/usr/local/include/pcre
注意后面不要加斜杠
 
首先,
mkdir  /usr/local/include/pcre
mkdir /usr/local/include/pcre/.libs
然后把pcre的包cp到指定路径下:
cp /opt/pcre/lib/libpcre.a /usr/local/include/pcre/libpcre.a
cp /opt/pcre/lib/libpcre.a /usr/local/include/pcre/libpcre.la
cp /opt/pcre/include/pcre.h /usr/local/include/pcre/pcre.h
cp  /usr/local/include/pcre/*.* /usr/local/include/pcre/.libs
 
/opt/pcrepcre的安装路径这里可自定,cp完文件后,我们将nginx配置安装
./configure --prefix=/opt/nginx --with-pcre=/usr/local/include/pcre
 
注意:
--with-pcre=/usr/local/include/pcre
这里必须是/usr/local/include/pcre路径,安装路径不行,这里尝试过了,否则失败后很头疼;
 
第二当编译好后,报如下错误:
make -f objs/Makefile
make[1]: Entering directory `/export/software/nginx/jdws-1.0'
cd /usr/local/include/pcre \
        && if [ -f Makefile ]; then make distclean; fi \
        && CC="gcc" CFLAGS="" \
        ./configure --disable-shared
/bin/sh: line 2: ./configure: ûÓÐÄǸöÎļþ»òĿ¼
make[1]: *** [/usr/local/include/pcre/Makefile] ´íÎó 127
make[1]: Leaving directory `/export/software/nginx/jdws-1.0'
make: *** [build] ´íÎó 2
 
我们修改nginx安装目录下的objs/MakeFile文件中的
/usr/local/include/pcre/Makefile:   objs/Makefile
     cd /usr/local/include/pcre \
      && if [ -f Makefile ]; then $(MAKE) distclean; fi \
      && CC="$(CC)" CFLAGS="" \
./configure --disable-shared
大约在994行,删除./configure --disable-shared这行内容后,然后make make install就没有问题了
 
 


10.          Nginx反向代理获取真实IP


proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;


11.          nginx 使用if错误


当出现如下错误是:
[emerg]: unknown directive "if($request_method" in /export/servers/nginx/conf/nginx.conf:86
一种是少pcre
另一种是:
if 和括号间需要空格,坑爹啊
 
 


12.           设定cache


add_header X-Cache '$upstream_cache_status from $server_addr';
 


13.          nginx cache状态缓存


proxy_cache_valid  200 304 20m;
如果要缓存内容,需要加上如上内容,这是对http状态值进行缓存,并且设定缓存时间。
 


14.          $request_uri


$request­_uri获取当前浏览器完整路径
 
$uri$is_args$args 这个是获取真实请求路径
 
 


15.          Rewrite需要写在location


rewrite404
后来查看到配置中rewrite serverlocation外,这样是有问题的,把rewrite放到location中就没问题了
 
 


16.          调试nginx


修改config并编译
由于gdb需要gcc的时候加上-g参数,这样生成的文件才能使用gdb调试,因此我们要对源码做一下小改动
修改auto/cc/conf文件
ngx_compile_opt="-c"
变为
ngx_compile_opt="-c -g"
执行configure
./configure --prefix=/home/yejianfeng/nginx/
确认
发现多出了objs文件夹,里面有Makefile文件
确认一下-g参数是否加上了
vim objs/Makefile
DSC0000.jpg
 


17.          Nginx 高并发设置


并发100时,nginx+php 可以到850,但是300-500并发却低到400-500,这不正常,所以需要对linux系统的环境进行设置
================================================================
vi /etc/sysctl.conf  CentOS5.5中可以将所有内容清空直接替换为如下内容:
net.ipv4.ip_forward = 0
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.default.accept_source_route = 0
kernel.sysrq = 0
kernel.core_uses_pid = 1
net.ipv4.tcp_syncookies = 1
kernel.msgmnb = 65536
kernel.msgmax = 65536
kernel.shmmax = 68719476736
kernel.shmall = 4294967296
net.ipv4.tcp_max_tw_buckets = 6000
net.ipv4.tcp_sack = 1
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_rmem = 4096 87380 4194304
net.ipv4.tcp_wmem = 4096 16384 4194304
net.core.wmem_default = 8388608
net.core.rmem_default = 8388608
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.core.netdev_max_backlog = 262144
net.core.somaxconn = 262144
net.ipv4.tcp_max_orphans = 3276800
net.ipv4.tcp_max_syn_backlog = 262144
net.ipv4.tcp_timestamps = 0
net.ipv4.tcp_synack_retries = 1
net.ipv4.tcp_syn_retries = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_mem = 94500000 915000000 927000000
net.ipv4.tcp_fin_timeout = 1
net.ipv4.tcp_keepalive_time = 30
net.ipv4.ip_local_port_range = 1024 65000
使配置立即生效可使用如下命令:
sysctl -p
==============================================================
/etc/security/limits.conf最后增加:
* soft nofile 65535
* hard nofile 65535
* soft nproc 65535
* hard nproc 65535
具体使用哪种,在 CentOS 中使用第种方式无效果,使用第种方式有效果,而在Debian 中使用第种有效果
 
参考:
http://hi.baidu.com/touchiyudeji/item/a699730b80ba78d9dde5b00e
 


18.          nginx 日志格式配置


 
       log_format main            '$remote_addr - $remote_user [$time_local] ' '-----"$request"------- $status $bytes_sent '
                                                       '"$http_referer" "$http_user_agent" '
                                                          '"$gzip_ratio"' '"addr:$upstream_addr - status:$upstream_status - cachestatus:$upstream_cache_status"'
                                                                                                  '- cacheKey:"$host:$server_port$request_uri"' ;
 
请求的upstream 的地址$upstream_addr
请求upstream 的状态$upstream_status
请求的upstream cache的状态$upstream_cache_status
 
 


19.          Nginx if 判断条件中的分组()不能超过9个,超过9个再非rewrite的会出现aborted问题


 
if ($request ~* .*/((1)|(2)|(3)|(4)|(5)|(6)|(7)|(8)|(9))){
 
}
 
这种情况下,非rewrite的内容将显示aborted问题,解决方式由多个if进行判断
 
 


20.          error_page 切换到指定的location


 
定义一个location ,@定义一个名称是外面无法访问的,一般用在try_fileserror_page
location @hhvm_error_to_php {
                include                 fastcgi_params;
   #             fastcgi_pass            unix:/dev/shm/php-fcgi.sock;
                fastcgi_pass            php_servers;
                fastcgi_index           index.php;
                fastcgi_param           SCRIPT_FILENAME /export/data/www/comm.360buy.com_test$fastcgi_script_name;
                fastcgi_connect_timeout 3;
                fastcgi_send_timeout 5;
                fastcgi_read_timeout 5;
 
 
        }
 
 
location ~ \.php$ {
           #################hhvm###############################################################################
            #edit date:20130724
            #edit author:huzhiguang
            #function: access url to hhvm
           ###################################################################################################
        if ($request ~* .*/(ProductPageService\.aspx|clubservice\.aspx|(productpage/p-(\d*)-s-(\d*)-t-(\d*)-p-(\d*)\.html.*)|(clubservice/newcomment-(.*)-(\d*)\.html.*))){
#当遇到错误时500 502 503 504时跳转到hhvm_error_to_php这个locationphp处理
                        error_page 500 502 503 504 = @hhvm_error_to_php ;
                        proxy_pass      http://hhvms;
              #if匹配中使用了break ,则下面不会再继续进行匹配,那么也就不用去判断非了
                        break;
        }
              #加上改行后,proxy返回500后,会拦截进行error_page处理,默认不处理
        proxy_intercept_errors on;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $remote_addr;
           ##################################################################################################
                include                 fastcgi_params;
 #               fastcgi_pass            unix:/dev/shm/php-fcgi.sock;
                fastcgi_pass            php_servers;
                fastcgi_index           index.php;
                fastcgi_param           SCRIPT_FILENAME /export/data/www/comm.360buy.com_test$fastcgi_script_name;
                fastcgi_connect_timeout 3;
                fastcgi_send_timeout 5;
                fastcgi_read_timeout 5;
         }
 
如果加上该行,php如果出现了500nginx会进行error_page处理,默认不处理
fastcgi_intercept_errors on;


21.          Nginx遇到访问aborted解决


nginx访问所有的aborted都不行时,配置又没有问题,reload也不生效时,然后将所有的nginx进行kill掉,然后重启就好了,
这个是我发现因为我更新了一个动态链接库:
libz.so.1 => /export/servers/hhvm-1.1/support_lib/libz.so.1 (0x00007fd912710000)
然后影响了nginx的运行,所以造成了这种reload无效的问题

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.iyunv.com/thread-319166-1-1.html 上篇帖子: 端口占用导致win7下无法启动nginx服务器 下篇帖子: 编写nginx模块一,hello模块
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表