您的位置:首页 > 运维架构 > Nginx

【Nginx学习】Nginx配置规则参数介绍

2016-06-14 18:12 330 查看
Nginx的配置涉及到很多方面,也比较复杂,今天支队nginx.conf的配置做一些简单说明。

一、配置基础

1.正则表达式

正则表达式匹配是Nginx中最基础的配置,以下是一些匹配符号说明:

~ 为区分大小写匹配

~* 为不区分大小写匹配

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

文件及目录匹配,其中:

-f和!-f用来判断是否存在文件

-d和!-d用来判断是否存在目录

-e和!-e用来判断是否存在文件或目录

-x和!-x用来判断文件是否可执行

flag标记有:

last 相当于Apache里的[L]标记,表示完成rewrite

break 终止匹配, 不再匹配后面的规则

redirect 返回302临时重定向 地址栏会显示跳转后的地址

permanent 返回301永久重定向 地址栏会显示跳转后的地址

二、http配置

server {} #定义一个虚拟主机

listen 80; #定义监听的地址和端口,默认监听在本机所有地址上

server_name NAME […]; #定义虚拟主机名,可以使用多个名称,还可以使用正则表达式或通配符。

sendfile on #开启 sendfile 调用来快速的响应客户端

keepalive_timeout 65 #长连接超时时间,单位是秒。

send_timeout #指定响应客户端的超时时间

client_max_body_size 10m #允许客户端请求的实体最大大小

root PATH #设置请求 URL 所对应资源所在文件系统上的根目录

location [ = | ~ | ~* | ^~ ] URI { … } #设置一个 URI 匹配路径

=:精确匹配

~:正则表达式匹配,区分字符大小写

~*:正则表达式匹配,不区分字符大小写

^~:URI 的前半部分匹配,且不实用正则表达式

优先级:

= > location 完整路径 > ^~ > ~ > ~* > location 起始路径 > location /

allow 和 deny #基于 IP 访问控制

配置实例

server {
listen 80;
server_name localhost;
root \web\qikuweb\www;
set $node_port 8360;

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;
}
if (-d $request_filename){
rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
}
location = /index.js {
proxy_http_version 1.1;
proxy_set_header Connection "";
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;
}

location ~ /static/ {
etag         on;
expires      max;
}
location ~* ^.+\.(ico|gif|jpg|jpeg|png|css|js|txt|xml|swf|wav)$ {
access_log   off;
expires      30d;
}

location ~* ^.+\.(eot|ttf|otf|woff|svg)$ {
access_log   off;
expires max;
}
location ~* ^.+\.(html|htm)$ {
expires      24h;
}
# 开启gzip
gzip on;

# 启用gzip压缩的最小文件,小于设置值的文件将不会压缩
gzip_min_length 1k;

# gzip 压缩级别,1-10,数字越大压缩的越好,也越占用CPU时间,后面会有详细说明
gzip_comp_level 2;

# 进行压缩的文件类型。javascript有多种形式。其中的值可以在 mime.types 文件中找到。
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png font/ttf font/otf image/svg+xml;

# 是否在http header中添加Vary: Accept-Encoding,建议开启
gzip_vary on;

# 禁用IE 6 gzip
gzip_disable "MSIE [1-6]\.";
}


先去健身了,回来在补全注释

参考文章

[ aoLiii]Nginx 配置详解
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  nginx