03月06, 2018

Nginx配置文件解释

Nginx配置一直是个非常头疼的问题,本文将持续对Nginx配置做归纳和解释。

server {
    listen     80;

    server_name www.daguanren.cc;    #服务器域名,同一服务器可以处理多个域名,所有访问www.daguanren.cc的请求,将做如下处理


    # note that these lines are originally from the "location /" block
    root   /usr/share/nginx/html;
    index index.php index.html index.htm;

    #add_header Access-Control-Allow-Origin *;
    # 这里如果我如果允许liumang.daguanren.cc来外链我的静态资源,我需要加入允许跨域
    add_header 'Access-Control-Allow-Origin' 'http://liumang.daguanren.cc';

    location / {
        #try_files $uri $uri/ =404;
        try_files $uri $uri/ /index.php?q=$uri&$args;
    }

    #必须要增加fastcgi_intercept_errors on;这个选项
    fastcgi_intercept_errors on;
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;

    location = /50x.html {
        root /usr/share/nginx/html;
    }

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }

    #压缩配置
    gzip            on;
    #设置允许压缩的页面最小字节数,页面字节数从header头的Content-Length中获取。默认值是0,不管页面多大都进行压缩。建议设置成大于1K。如果小于1K可能会越压越大。
    gzip_min_length 1000;
    #压缩缓冲区大小。表示申请4个单位为16K的内存作为压缩结果流缓存,默认值是申请与原始数值大小相同的内存空间来存储gzip压缩结果。
    gzip_buggers 4 16k;
    gzip_comp_level 2;
    #压缩比率。用来指定GZIP压缩比,1压缩比最小,处理速度最快;9压缩比最大,传输速度最快,但处理最慢,比较消耗CPU资源;
    gzip_proxied    expired no-cache no-store private auth;
    #用来指定压缩的类型,"text/html"类型总是会被压缩。
    gzip_types      text/plain application/xml;
    #vary header支持。该选项可以让前端的缓存服务器缓存经过GZIP压缩的页面;
    gzip_vary_on;

}


server {
        listen 80;
        server_name nginx.daguanren.cc;    #所有访问nginx.daguanren.cc的请求将做如下处理
        root /home/app/daguanren;

        #这里是设置变量为1234
        set $node_port 1234;

        index index.js index.html index.htm;

        if ( -f $request_filename/index.html ){
            rewrite (.*) $1/index.html break;
        }
        if ( !-f $request_filename ){
            rewrite (.*) /index.js;
        }

        #这里将请求由127.0.0.1:1234代为处理
        location = /index.js {
            proxy_http_version 1.1;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header Host $http_host;
            proxy_set_header X-NginX-Proxy true;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_pass http://127.0.0.1:$node_port$request_uri;
            proxy_redirect off;
        }

        #这里是静态文件夹不走NodeJS,直接走Nginx,缓存时间expires;对于图片、css和js修改的次数较少可以设置缓存;
        location ~ /static/ {
            etag         on;
            expires      max;
        }
}

具体location的写法可以参照:

location  = / {
  #以=开头表示精确匹配
  # 精确匹配 / ,主机名后面不能带任何字符串
  # 这里只匹配根目录结尾的请求,后面不能带任何字符串。
  [ configuration A ]
}

location  / {
  # 因为所有的地址都以 / 开头,所以这条规则将匹配到所有请求
  # / 通用匹配, 如果没有其它匹配,任何请求都会匹配到
  # 但是正则和最长字符串会优先匹配
  [ configuration B ]
}

location /documents/ {
  # 匹配任何以 /documents/ 开头的地址,匹配符合以后,还要继续往下搜索
  # 只有后面的正则表达式没有匹配到时,这一条才会采用这一条
  [ configuration C ]
}

location ~ /documents/Abc {
  # 匹配任何以 /documents/Abc 开头的地址,匹配符合以后,还要继续往下搜索
  # ~ 开头表示区分大小写的正则匹配;
  # 只有后面的正则表达式没有匹配到时,这一条才会采用这一条
  [ configuration CC ]
}

location ^~ /images/ {
  #^~ 开头表示uri以某个常规字符串开头,不是正则匹配
  # 匹配任何以 /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

使用建议:

所以实际使用中,个人觉得至少有三个匹配规则定义,如下:
#直接匹配网站根,通过域名访问网站首页比较频繁,使用这个会加速处理,官网如是说。
#这里是直接转发给后端应用服务器了,也可以是一个静态首页
# 第一个必选规则
location = / {
    proxy_pass http://tomcat:8080/index
}
# 第二个必选规则是处理静态文件请求,这是nginx作为http服务器的强项
# 有两种配置模式,目录匹配或后缀匹配,任选其一或搭配使用
location ^~ /static/ {
    root /webroot/static/;
}
location ~* \.(gif|jpg|jpeg|png|css|js|ico)$ {
    root /webroot/res/;
}
#第三个规则就是通用规则,用来转发动态请求到后端应用服务器
#非静态文件请求就默认是动态请求,自己根据实际把握
#毕竟目前的一些框架的流行,带.php,.jsp后缀的情况很少了
location / {
    proxy_pass http://tomcat:8080/
}

HTTP状态码

200 - OK,服务器成功返回网页 
    - Standard response for successful HTTP requests.

301 - Moved Permanently(永久跳转),请求的网页已永久跳转到新位置。
    - This and all future requests should be directed to the given.

403 - Forbidden(禁止访问),服务器拒绝请求
    - forbidden request (matches a deny filter) => HTTP 403
    - The request was a legal request, but the server is refusing to respond to it.

404 - Not Found,服务器找不到请求的页面。
    - The requested resource could not be found but may be available again in the future.

500 - Internal Server Error(内部服务器错误)
    - internal error in haproxy => HTTP 500
    - A generic error message, given when no more specific message is suitable.

502 - Bad Gateway(坏的网关),一般是网关服务器请求后端服务时,后端服务没有按照http协议正确返回结果。
    - the server returned an invalid or incomplete response => HTTP 502
    - The server was acting as a gateway or proxy and received an invalid response from the upstream server.

503 - Service Unavailable(服务当前不可用),可能因为超载或停机维护。
    - no server was available to handle the request => HTTP 503
    - The server is currently unavailable (because it is overloaded or down for maintenance).

504 - Gateway Timeout(网关超时),一般是网关服务器请求后端服务时,后端服务没有在特定的时间内完成服务。
    - the server failed to reply in time => HTTP 504
    - The server was acting as a gateway or proxy and did not receive a timely response from the upstream server.

参考:

http://seanlook.com/2015/05/17/nginx-location-rewrite/

http://blog.51cto.com/oldboy/716294

nginx正则

nginx重定向问题深度分析

本文链接:https://www.daguanren.cc/post/nginx_configuration_explanation.html

-- EOF --

Comments