Nginx经验总结(持续更新)

1. post方法请求静态文件
默认情况下,web服务器都不允许post方法请求静态文件,会返回响应403 Not Allowed。但是有些时候确实有这种需求。可以通过配置文件来改变这种设置:在需要处理静态文件的location里这样配置即可,
location /static/ {
    root /path/to/files/;
    error_page 405 =200 $uri;
}
2. Nginx默认一次只能发送50个子请求(subrequest)
在nginx源码中,src/http/ngx_http_request.h文件中:
#define NGX_HTTP_MAX_SUBREQUESTS        50
在使用Openresty时,可以向configure脚本传参 置这个限制, ./configure --with-cc-opt="-D NGX_HTTP_MAX_SUBREQUESTS=250"
3. Nginx location匹配规则
匹配顺序:
a. 字符串匹配,和location块的顺序无关,根据uri匹配所有的location,从而得到一个匹配度最大的location。
b. 正则匹配,按照location块的顺序从前向后,如果找到匹配的location,则直接由该location处理请求。如果所有的location都不匹配,则由在字符串匹配中,匹配度最大的location处理。
匹配规则:
= /uri/   ——字符串精确匹配
^~ /uri/ ——字符串前缀匹配
~ /uri/   ——大小写区分的正则匹配
~* /uri/ ——大小写不区分的正则匹配
@ /uri/ ——命名location,只用于内部重定向请求
其中,如果=和^~匹配成功之后会立即停止搜索,即不再进行正则匹配。
4. 监控Nginx的状态
需要HttpStubStatusModule模块,默认情况是不开启的,所以需要编译时,指定开启这个模块。
./configure --with-http_stub_status_modules
nginx的配置:
location /nginx_status {
  # copied from http://blog.kovyrin.net/2006/04/29/monitoring-nginx-with-rrdtool/
  stub_status on;
  access_log   off;
  allow SOME.IP.ADD.RESS;
  deny all;
}
然后通过浏览器访问localhost/nginx_status,浏览器显示Nginx的状态
Active connections: 291
server accepts handled requests
  16630948 16630948 31070465
Reading: 6 Writing: 179 Waiting: 106
5. Nginx启用aio
默认Nginx是没有开启aio的,需要在配置编译时,加上相应选项否则启动Nginx会报错 unknown directive “aio”。
./configure --with-file-aio
6. 限制请求内容的大小
指令:client_max_body_size,用于设置这个值,默认是1m。context可以是http,server或者location。
7. 通过echo模块合并静态文件请求
正常html中包含多个js文件或者css文件,那么浏览器需要多次http请求才能完成这些文件的加载。比如html文件:
<html>
<head>
    <script type='text/javascript' src='/static/a.js'></script>
    <script type='text/javascript' src='/static/b.js'></script>
    <script type='text/javascript' src='/static/c.js'></script>
……
</html>
那么就需要3次请求。下面介绍echo模块实现请求合并。先修改html:
<html>
<head>
    <script type='text/javascript' src='/merge?/static/a.js&/static/b.js&/static/c.js'></script>
……
</html>
nginx配置文件:
location /static/ {
    root /home/www/doc_root;
}

location /merge {
    default_type 'text/javascript';

    echo_foreach_split '&' $query_string;    # 将查询字符串以&分割
        echo_location_async $echo_it;        # 发送子请求到$echo_it对应的location
        echo;
    echo_end;
}
通过这种方式可以有效减少客户端请求,降低服务器端的压力。
8. nginx开启gzip

gzip    on;    # 开启gzip,默认关闭
gzip_comp_level    5;    # 压缩级别,1-9,级别越高压缩率越高,但是相应的耗cpu
gzip_min_length    1025;    # 当响应内容大小大于多少bytes后使用gzip
gzip_types    text/plain application/x-javascript application/json text/javascript text/css    # 对于什么类型的内容使用gzip



  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值