1、基本配置
user www-data;
worker_processes 8; #工作进程数,最好配置为CPU核数~CPU核数*2之间
pid /run/nginx.pid;
events {
worker_connections 1024; #单个工作进程的最大连接数
multi_accept on;
#epoll是多路复用IO(I/O Multiplexing)中的一种方式,
#仅用于linux2.6以上内核,可以大大提高nginx的性能
use epoll;
}
http {
#sendfile 指令指定 nginx 是否调用 sendfile 函数(zero copy 方式)来输出文件,
#对于普通应用,必须设为 on,
#如果用来进行下载等应用磁盘IO重负载应用,可设置为 off,
#以平衡磁盘与网络I/O处理速度,降低系统的uptime.
sendfile on;
tcp_nopush on;
tcp_nodelay on;
#连接超时时间
keepalive_timeout 65;
types_hash_max_size 2048;
#设定mime类型,类型由mime.type文件定义
include /etc/nginx/mime.types;
default_type application/octet-stream;
proxy_ignore_client_abort on;
#日志格式
log_format json '{"@timestamp":"$time_iso8601",'
'"@version":"1",'
'"host":"$server_addr",'
'"client":"$remote_addr",'
'"http_x_forwarded_for":"$http_x_forwarded_for",'
'"size":$body_bytes_sent,'
'"responsetime":$request_time,'
'"domain":"$host",'
'"url":"$uri",'
'"status":"$status"}';
access_log /var/log/nginx/access.log json;
error_log /var/log/nginx/error.log;
#gzip设置
gzip on;
gzip_disable "msie6";
gzip_proxied any;
gzip_min_length 1000;
gzip_comp_level 4;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
#nginx缓存设置
proxy_cache_path /data/cache levels=1:2 keys_zone=cache:100m inactive=60m;
proxy_cache_key "$scheme$request_method$host$request_uri";
upstream server {
server localhost:8080;
}
upstream backend {
server localhost:8081;
}
server{
listen 80;
#配置域名
server_name service.test.com;
index index.html index.htm;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
#重写url
location /server/rest/cache {
rewrite /server/rest/cache/(.*) /service/cache/$1 last;
}
location /service/cache/ {
client_max_body_size 500m;
client_body_buffer_size 128k;
proxy_pass http://server/;
#设置header 解决获取用户真实IP的问题
proxy_set_header Host $host:$server_port;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#缓存配置
proxy_cache cache ;
add_header X-Proxy-Cache $upstream_cache_status;
proxy_cache_valid 200 1m;
proxy_cache_methods GET;
#设置httpVersion
proxy_http_version 1.1;
proxy_set_header Connection "";
}
}
server{
listen 443;
server_name service.test.com;
index index.html index.htm;
error_page 500 502 503 504 /50x.html;
#开启https
ssl on;
ssl_certificate /etc/nginx/live/service.test.com/fullchain.pem;
ssl_certificate_key /etc/nginx/live/service.test.com/privkey.pem;
location = /50x.html {
root /usr/share/nginx/html;
}
}
2、location
语法规则: location [=|||^~] /uri/ { … }
= 开头表示精确匹配
^~ 开头表示uri以某个常规字符串开头,理解为匹配 url路径即可。nginx不对url做编码,因此请求为/static/20%/aa,可以被规则^~ /static/ /aa匹配到(注意是空格)。
~ 开头表示区分大小写的正则匹配
~ 开头表示不区分大小写的正则匹配
!和!*分别为区分大小写不匹配及不区分大小写不匹配 的正则
/ 通用匹配,任何请求都会匹配到。
多个location配置的情况下匹配顺序为(参考资料而来,还未实际验证,试试就知道了,不必拘泥,仅供参考):
首先匹配 =,其次匹配^~, 其次是按文件中顺序的正则匹配,最后是交给 / 通用匹配。当有匹配成功时候,停止匹配,按当前匹配规则处理请求。
网友评论