配置

1.通用配置

#定义 Nginx 运行的用户和用户组,默认由 nobody 账号运行, windows 下面可以注释掉。
user  nobody; 
 
#nginx进程数,建议设置为等于CPU总核心数。可以和worker_cpu_affinity配合
worker_processes  1; 
 
#全局错误日志定义类型,[ debug | info | notice | warn | error | crit ]
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
 
#进程文件,window下可以注释掉
#pid        logs/nginx.pid;
 
# 一个nginx进程打开的最多文件描述符(句柄)数目,理论值应该是最多打开文件数(系统的值ulimit -n)与nginx进程数相除,
# 但是nginx分配请求并不均匀,所以建议与ulimit -n的值保持一致。
worker_rlimit_nofile 65535;
 
#工作模式与连接数上限
events {
    # 参考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; 
    # epoll模型是Linux 2.6以上版本内核中的高性能网络I/O模型,如果跑在FreeBSD上面,就用kqueue模型。
   #use epoll;
   #connections 20000;  # 每个进程允许的最多连接数
   # 单个进程最大连接数(最大连接数=连接数*进程数)该值受系统进程最大打开文件数限制,需要使用命令ulimit -n 查看当前设置
   worker_connections 65535;
}
 
#设定http服务器
http {
    #文件扩展名与文件类型映射表
    #include 是个主模块指令,可以将配置文件拆分并引用,可以减少主配置文件的复杂度
    include       mime.types;
    #默认文件类型
    default_type  application/octet-stream;
    #charset utf-8; #默认编码
 
    #定义虚拟主机日志的格式
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
    
    #定义虚拟主机访问日志
    #access_log  logs/access.log  main;
 
    #开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。
    sendfile        on;
    #autoindex on; #开启目录列表访问,合适下载服务器,默认关闭。
 
    #防止网络阻塞
    #tcp_nopush     on;
 
    #长连接超时时间,单位是秒,默认为0
    keepalive_timeout  65;
 
    # gzip压缩功能设置
    gzip on; #开启gzip压缩输出
    gzip_min_length 1k; #最小压缩文件大小
    gzip_buffers    4 16k; #压缩缓冲区
    gzip_http_version 1.0; #压缩版本(默认1.1,前端如果是squid2.5请使用1.0)
    gzip_comp_level 6; #压缩等级
    #压缩类型,默认就已经包含text/html,所以下面就不用再写了,写上去也不会有问题,但是会有一个warn。
    gzip_types text/plain text/css text/javascript application/json application/javascript application/x-javascript application/xml;
    gzip_vary on; //http头有关系,加个vary头,给代理服务器用的,有的浏览器支持压缩,有的不支持,所以避免浪费不支持的也压缩,所以根据客户端的HTTP头来判断,是否需要压缩
    #limit_zone crawler $binary_remote_addr 10m; #开启限制IP连接数的时候需要使用
 
    # http_proxy服务全局设置
    client_max_body_size   10m;
    client_body_buffer_size   128k;
    proxy_connect_timeout   75;
    proxy_send_timeout   75;
    proxy_read_timeout   75;
    proxy_buffer_size   4k;
    proxy_buffers   4 32k;
    proxy_busy_buffers_size   64k;
    proxy_temp_file_write_size  64k;
    proxy_temp_path   /usr/local/nginx/proxy_temp 1 2;
 
   # 设定负载均衡后台服务器列表 
    upstream  backend.com  { 
        #ip_hash; # 指定支持的调度算法
        # upstream 的负载均衡,weight 是权重,可以根据机器配置定义权重。weigth 参数表示权值,权值越高被分配到的几率越大。
        server   192.168.10.100:8080 max_fails=2 fail_timeout=30s ;  
        server   192.168.10.101:8080 max_fails=2 fail_timeout=30s ;  
    }
 
    #虚拟主机的配置
    server {
        #监听端口
        listen       80;
        #域名可以有多个,用空格隔开
        server_name  localhost fontend.com;
        # Server Side Include,通常称为服务器端嵌入
        #ssi on;
        #默认编码
        #charset utf-8;
        #定义本虚拟主机的访问日志
        #access_log  logs/host.access.log  main;
        
        # 因为所有的地址都以 / 开头,所以这条规则将匹配到所有请求
        location / {
            root   html;
            index  index.html index.htm;
        }
        
        #error_page  404              /404.html;
 
        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
 
       # 图片缓存时间设置
       location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ {
          expires 10d;
       }
 
       # JS和CSS缓存时间设置
       location ~ .*.(js|css)?$ {
          expires 1h;
       }
 
        #代理配置
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #location /proxy/ {
        #    proxy_pass   http://127.0.0.1;
        #}
 
        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}
 
        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }
 
    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;
 
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
 
    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;
 
    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;
 
    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;
 
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;
 
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

2.负载均衡

通过在 upstream 参数中添加的应用服务器 IP 后添加指定参数即可实现

#error_log  logs/error.log  info;
#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    upstream testsite.com{
        #weight 值越大,负载权重越大,请求次数越多             
             #max_fails 允许请求失败的次数,超过失败次数后,转发到下一个服务器,当有max_fails个请求失败,就表示后端的服务器不可用,默认为1,将其设置为0可以关闭检查   
             #fail_timeout 指定时间内无响应则失败, 在以后的fail_timeout时间内nginx不会再把请求发往已检查出标记为不可用的服务器
             #down 表示当前server不参与负载
             #backup 其他非backup server都忙的时候,backup server作为备用服务器,将请求转发到backup服务器
             server 192.168.10.150:8080 weight=1 max_fails=2 fail_timeout=30s;
             server 192.168.10.151:8080 weight=2 max_fails=2 fail_timeout=30s;
             server 192.168.10.152:8080 down;
             #server 192.168.10.153:8080 myupstream;
    }
    server {
        listen       80;
        server_name  localhost;

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        location / {
            proxy_pass  http://testsite.com;
            proxy_redirect default;
            #这里配置宕机检测,都设置为1秒,这是有了负载均衡过后配置的,如果访问时挂了一个服务器,1秒不响应就自动切换到另外应用服务器进行访问
            proxy_connect_timeout 1;
            proxy_send_timeout 1;
            proxy_read_timeout 1;
        }

    }


}

PS: 使用服务器组 upstream 注意后面的斜杠

location / {
          proxy_pass http://testsite.com;
       proxy_redirect default;
}
#http://testsite.com末尾可以不用加 /
 
location /other/ {
          proxy_pass http://testsite.com/;
       proxy_redirect default;
}
#http://testsite.com 之后一定要加 /

3.反向代理

主要是多个 location 项对应不同的微服务。通过地址前缀区分。使用 include 进行配置拆分。

主 nginx.conf 配置

#user  root;
worker_processes  8;
events {
    worker_connections  1024;
}

http {
    include       mime.types;
    underscores_in_headers on;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  logs/access.log  main;

    sendfile        on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout  180;

    gzip  on;
    gzip_min_length 2k;
    gzip_buffers 4 64k;
    gzip_comp_level 2;
    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;
    gzip_vary off;
    gzip_disable "MSIE [1-6]\.";
   
    send_timeout 60s;
    client_header_timeout 15s;
    client_body_timeout 15s;
    client_max_body_size   10m;
    client_body_buffer_size   512k;
    
    include /data/nginx/nginx2.conf;
}

nginx2.conf 配置

proxy_pass :为项目的实际访问地址,如果路径没有 / 实际路径会拼上 location 匹配路径。如果有 / 结尾

会去掉匹配的路径段,但是后续的 url 还是可以拼上去的。

server {
        listen  8080;
        server_name  192.168.100.81;

		 location / {
            root   html;
            index  index.html index.htm;
        }
 
        location ~ /get/system {
                proxy_set_header Host $host;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
                proxy_set_header X-Forwarded-Proto http;
                proxy_http_version 1.1;
                proxy_connect_timeout 4s; 
                proxy_read_timeout 7200s; 
                proxy_send_timeout 12s; 
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection "upgrade";
                proxy_pass http://192.168.100.81:10083;
        }
 
}

反向代理判断 header 条件头选择负载


    location ^~ /ivory/system {
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto http;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "upgrade";
            proxy_connect_timeout 4s;
            client_max_body_size 2000m;
            proxy_read_timeout 3600s;
            proxy_send_timeout 12s;
			
			if ($http_cluster = "south") {
				proxy_pass http://192.168.60.163:10083;
				break;
			}
            proxy_pass http://192.168.60.156:10083;

    }

4.正向代理

原因是 Nginx 0.6.18以后的版本中 http{} 启用了一个resolver指令,此外,如果有 ipv6 环境的机器,还可以加resolver 8.8.8.8 ipv6=off;

worker_processes  1;
events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
server {
    resolver 114.114.114.114;       #指定DNS服务器IP地址
    listen       880 default_server;
    location / {
        proxy_pass http://$host$request_uri;     #设定代理服务器的协议和地址 
                proxy_set_header HOST $host;
                proxy_buffers 256 4k;
                proxy_max_temp_file_size 0k;
                proxy_connect_timeout 30;
                proxy_send_timeout 60;
                proxy_read_timeout 60;
                proxy_next_upstream error timeout invalid_header http_502;
    }
}
server {
    resolver 114.114.114.114;       #指定DNS服务器IP地址
    listen       443 default_server;
    location / {
        proxy_pass https://$host$request_uri;     #设定代理服务器的协议和地址 
                proxy_set_header HOST $host;
                proxy_buffers 256 4k;
                proxy_max_temp_file_size 0k;
                proxy_connect_timeout 30;
                proxy_send_timeout 60;
                proxy_read_timeout 60;
                proxy_next_upstream error timeout invalid_header http_502;
    }
}
    server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.htm {
            root   html;
        }
    }
}

匹配优先级

模式 含义
location = /uri = 表示精确匹配,只有完全匹配上才能生效
location ^~ /uri ^~ 开头对URL路径进行前缀匹配,并且在正则之前。
location ~ pattern 开头表示区分大小写的正则匹配
location ~* pattern 开头表示不区分大小写的正则匹配
location /uri 不带任何修饰符,也表示前缀匹配,但是在正则匹配之后
location / 通用匹配,任何未匹配到其它location的请求都会匹配到,相当于switch中的default
  • 首先精确匹配 =
  • 其次前缀匹配 ^~
  • 其次是按文件中顺序的正则匹配
  • 然后匹配不带任何修饰的前缀匹配。
  • 最后是交给 / 通用匹配
  • 当有匹配成功时候,停止匹配,按当前匹配规则处理请求

root alias

location /img/ {
    alias /var/www/image/;
}#若按照上述配置的话,则访问/img/目录里面的文件时,ningx会自动去/var/www/image/目录找文件

location /img/ {
    root /var/www/image;
}#若按照这种配置的话,则访问/img/目录下的文件时,nginx会去/var/www/image/img/目录下找文件。]

认证

http 参数认识

  • X-Frame-Options

    点击劫持,控制能否给 iframe 内嵌,DENY:不能被嵌入到任何iframe或者frame中。 SAMEORIGIN:页面只能被本站页面嵌入到iframe或者frame中 。ALLOW-FROM uri:只能被嵌入到指定域名的框架中

  • referer

    当浏览器向web服务器发送请求时, 一般会带上Referer请求头,告诉服务器请求时从哪个页面链接过来的,服务器以此可以获得一部分信息用于处理

关于反向代理的前缀问题

有个需求,去掉前缀

http://myserver:80/foo/bar 反向代理到后台端 http://localhost:3200/bar

两种方法,第二种是最正确的

第一种

location  /foo {
  rewrite /foo/(.*) /$1  break;
  proxy_pass         http://localhost:3200;
  proxy_redirect     off;
  proxy_set_header   Host $host;
}

第二种

location /foo {
  proxy_pass http://localhost:3200/;
}
上次更新时间: 2024/5/7 05:59:02