nginx相关.md

简书迁移

Posted by thrfox on June 29, 2020

alias和root区别

1
2
3
4
5
6
7
8
9
location ^~ /t/ {
     root /www/root/html/;
}
# 如果一个请求的URI是/t/a.html时,web服务器将会返回服务器上的/www/root/html/t/a.html的文件。

location ^~ /t/ {
 alias /www/root/html/new_t/;
}
# 如果一个请求的URI是/t/a.html时,web服务器将会返回服务器上的/www/root/html/new_t/a.html的文件。

nginx二级目录配置vue-cli问题

(生成的css文件中background url()图片路径问题)[https://github.com/vuejs/vue-loader/issues/481]

1
2
3
4
5
    location ^~/mobile/ {
		  try_files $uri $uri/ /mobile/index.html;  # 注意这里是/mobile/index.html 而不是mobile/index.html
      alias  html/mobile/;
      index  index.html index.htm;
    }

重定向

1
2
3
4
  server {
    server_name www.example.com;
    rewrite ^ http://example.com$request_uri? permanent;
  }

生成自签名证书

  • 用于开发环境中的https

    ```bash apt-get update apt-get install openssl

openssl genrsa -des3 -out ssl_passphrase.key 2048 # 生成私钥.key-提示输入密码 cp ssl_passphrase.key ssl.key openssl rsa -in ssl.key -out ssl.key # 2.这一步主要是为了清除上一步输入的密码 openssl req -new -key ssl.key -out ssl.csr # 用私钥.key生成请求获取证书的信息.csr - Common Name 时输入IP或域名,其他可以为空 openssl x509 -req -days 3650 -in ssl.csr -signkey ssl.key -out ssl.crt #自己作为CA机构传入.key和.csr后,签发证书.crt, cat ssl.key ssl.crt > ssl.pem #证书重写成.pem格式

1
2
3
4
5
6
7
8
9
10
11
12
[.key .csr .crt .pem 区别](https://crypto.stackexchange.com/questions/43697/what-is-the-difference-between-pem-csr-key-and-crt)


### nginx配置白名单访问(限制国家、地图)
```sh
#安装GeoIP
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
#解压
gunzip GeoIP.dat.gz
gunzip GeoLiteCity.dat.gz
#配置nginx.conf
  • 配置nginx.conf
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
    http{
    geoip_country /etc/nginx/GeoIP.dat;  #路径、文件名为你存放GeoIP.dat的路径和文件名
    map $geoip_country_code $allowed_country {
      default no; #设定默认值yes 或 no,默认通过或者默认拒绝
      CN yes; #国家 yes就是允许哪个国家访问
    }
    server {
            listen 80;
            server_name xxx.com;
            
            if ($allowed_country = no) { # 添加判断,如果访问国家=no,就返回403
                return 403;
            }
    
    }
    }
    
  • nginx配置详解

    ```conf #nginx进程数,通常设置成和cpu的数量相等 worker_processes auto;

#全局错误日志定义类型,[debug | info | notice | warn | error | crit] #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; error_log /var/log/nginx/error.log; #进程pid文件 pid /run/nginx.pid;

events { #参考事件模型,use [ kqueue | rtsig | epoll | /dev/poll | select | poll ]; epoll模型 #是Linux 2.6以上版本内核中的高性能网络I/O模型,linux建议epoll,如果跑在FreeBSD上面,就用kqueue模型。 #补充说明: #与apache相类,nginx针对不同的操作系统,有不同的事件模型 #A)标准事件模型 #Select、poll属于标准事件模型,如果当前系统不存在更有效的方法,nginx会选择select或poll #B)高效事件模型 #Kqueue:使用于FreeBSD 4.1+, OpenBSD 2.9+, NetBSD 2.0 和 MacOS X.使用双处理器的MacOS X系统使用kqueue可能会造成内核崩溃。 #Epoll:使用于Linux内核2.6版本及以后的系统。 #/dev/poll:使用于Solaris 7 11/99+,HP/UX 11.22+ (eventport),IRIX 6.5.15+ 和 Tru64 UNIX 5.1A+。 #Eventport:使用于Solaris 10。 为了防止出现内核崩溃的问题, 有必要安装安全补丁。 # use epoll

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#单个进程最大连接数(最大连接数=连接数+进程数)
#根据硬件调整,和前面工作进程配合起来用,尽量大,但是别把cup跑到100%就行。
worker_connections  1024;

#keepalive 超时时间
keepalive_timeout 60;

#客户端请求头部的缓冲区大小。这个可以根据你的系统分页大小来设置,一般一个请求头的大小不会超过1k,不过由于一般系统分页都要大于1k,所以这里设置为分页大小。
#分页大小可以用命令getconf PAGESIZE 取得。
#[root@web001 ~]# getconf PAGESIZE
#但也有client_header_buffer_size超过4k的情况,但是client_header_buffer_size该值必须设置为“系统分页大小”的整倍数。
#client_header_buffer_size 4k;

#这个将为打开文件指定缓存,默认是没有启用的,max指定缓存数量,建议和打开文件数一致,inactive是指经过多长时间文件没被请求后删除缓存。
#open_file_cache max=65535 inactive=60s;

#这个是指多长时间检查一次缓存的有效信息。
#语法:open_file_cache_valid time 默认值:open_file_cache_valid 60 使用字段:http, server, location 这个指令指定了何时需要检查open_file_cache中缓存项目的有效信息.
#open_file_cache_valid 80s;

#open_file_cache指令中的inactive参数时间内文件的最少使用次数,如果超过这个数字,文件描述符一直是在缓存中打开的,如上例,如果有一个文件在inactive时间内一次没被使用,它将被移除。
#语法:open_file_cache_min_uses number 默认值:open_file_cache_min_uses 1 使用字段:http, server, location  这个指令指定了在open_file_cache指令无效的参数中一定的时间范围内可以使用的最小文件数,如果使用更大的值,文件描述符在cache中总是打开状态.
#open_file_cache_min_uses 1;

#语法:open_file_cache_errors on | off 默认值:open_file_cache_errors off 使用字段:http, server, location 这个指令指定是否在搜索一个文件是记录cache错误.
#open_file_cache_errors on; }

#设定http服务器,利用它的反向代理功能提供负载均衡支持 http { #文件扩展名与文件类型映射表 include mime.types;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
#默认文件类型
default_type  application/octet-stream;

#默认编码
charset utf-8;

#服务器名字的hash表大小
#保存服务器名字的hash表是由指令server_names_hash_max_size 和server_names_hash_bucket_size所控制的。参数hash bucket size总是等于hash表的大小,并且是一路处理器缓存大小的倍数。在减少了在内存中的存取次数后,使在处理器中加速查找hash表键值成为可能。如果hash bucket size等于一路处理器缓存的大小,那么在查找键的时候,最坏的情况下在内存中查找的次数为2。第一次是确定存储单元的地址,第二次是在存储单元中查找键 值。因此,如果Nginx给出需要增大hash max size 或 hash bucket size的提示,那么首要的是增大前一个参数的大小.
server_names_hash_bucket_size 512;

#客户端请求头部的缓冲区大小。这个可以根据你的系统分页大小来设置,一般一个请求的头部大小不会超过1k,不过由于一般系统分页都要大于1k,所以这里设置为分页大小。分页大小可以用命令getconf PAGESIZE取得。
client_header_buffer_size 32k;

#客户请求头缓冲大小。nginx默认会用client_header_buffer_size这个buffer来读取header值,如果header过大,它会使用large_client_header_buffers来读取。
large_client_header_buffers 4 32k;

#设定通过nginx上传文件的大小
client_max_body_size 50m;

#开启高效文件传输模式,sendfile指令指定nginx是否调用sendfile函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络I/O处理速度,降低系统的负载。注意:如果图片显示不正常把这个改成off。
#sendfile指令指定 nginx 是否调用sendfile 函数(zero copy 方式)来输出文件,对于普通应用,必须设为on。如果用来进行下载等应用磁盘IO重负载应用,可设置为off,以平衡磁盘与网络IO处理速度,降低系统uptime。
sendfile   on;

#开启目录列表访问,合适下载服务器,默认关闭。
#autoindex on;

#此选项允许或禁止使用socke的TCP_CORK的选项,此选项仅在使用sendfile的时候使用
tcp_nopush on;
tcp_nodelay on;

#长连接超时时间,单位是秒
keepalive_timeout 60;

#FastCGI相关参数是为了改善网站的性能:减少资源占用,提高访问速度。下面参数看字面意思都能理解。
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 256k;
fastcgi_intercept_errors on;

#gzip模块设置
gzip on; #开启gzip压缩输出
gzip_min_length  1k; #最小压缩文件大小
gzip_buffers     16 8k; #压缩缓冲区
gzip_http_version 1.1; #压缩版本(默认1.1,前端如果是squid2.5请使用1.0)
gzip_comp_level 6; #压缩等级

#压缩类型,默认就已经包含textml,所以下面就不用再写了,写上去也不会有问题,但是会有一个warn。
gzip_types     text/plain application/javascript application/x-javascript text/javascript text/css application/xml; 
gzip_vary on;
gzip_proxied   expired no-cache no-store private auth;
gzip_disable   "MSIE [1-6]\.";

#开启限制IP连接数的时候需要使用
limit_conn_zone $binary_remote_addr zone=perip:10m;
limit_conn_zone $server_name zone=perserver:10m;

server_tokens off;
access_log off;

server {

  listen 8080 ssl;
  server_name 192.168.10.100;
   		
  # 自己的证书,放在与nginx.conf同一文件夹下。(若放不同文件夹注意路径问题)
  ssl_certificate /etc/nginx/cert/ssl.pem;
  ssl_certificate_key /etc/nginx/cert/ssl.key;
   		
  ssl_session_timeout 5m;
  ssl_session_cache shared:SSL:10m;
  ssl_protocols TLSv1 TLSv1.1 TLSv1.2 SSLv2 SSLv3;
  ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
  ssl_prefer_server_ciphers on;
  ssl_verify_client off; # SSL双向校验

  # 加下面一行,http就能跳转到https,非443、80端口时也可用
  error_page 497 301 https://$http_host$request_uri;
   		
  location / {		
      proxy_redirect off;
      proxy_pass http://patrolsystem:8080;      # 转发

      proxy_set_header Host $http_host;   # 使用上面的ip和端口,否则默认为proxy_pass的IP和端口
      proxy_set_header X-Forwarded-Proto  $scheme; # 使用上面的https scheme
      proxy_set_header X-Forwarded-Uri  $request_uri;
      proxy_set_header X-Real-IP        $remote_addr; # 访问的真实地址
      proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for; # X-Forwarded-For头信息可以有多个,中间用逗号分隔,第一项为真实的客户端ip,剩下的就是曾经经过的代理或负载均衡的ip地址,经过几个就会出现几个。
      proxy_set_header X-NginX-Proxy true;

      proxy_http_version 1.1;
      proxy_set_header Upgrade $http_upgrade;   # 升级协议头
      proxy_set_header Connection upgrade;
  }

  location ^~/api/ { # 已该api为前缀的请求全部转发到8301,如xxx/api/auth,则发送到8301/auth
	    proxy_set_header Host $http_host;   # 使用上面的ip和端口,否则默认为proxy_pass的IP和端口
		  proxy_set_header X-Forwarded-Proto  $scheme; # 使用上面的https scheme
    proxy_set_header X-Forwarded-Uri  $request_uri;
    proxy_set_header X-Real-IP        $remote_addr; # 访问的真实地址
    proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for; # X-Forwarded-For头信息可以有多个,中间用逗号分隔,第一项为真实的客户端ip,剩下的就是曾经经过的代理或负载均衡的ip地址,经过几个就会出现几个。
    proxy_set_header X-NginX-Proxy true;

	    rewrite ^/api/(.*)$ /$1 break; # 重写api前缀
    proxy_pass http://patrol-gateway:8301;
  }

  location ^~/api2/ { # 已该api2为前缀的请求,去除api2前缀后,全部转发,如xxx/api2/auth,则发送到xxx/auth
	    proxy_set_header Host $http_host;   # 使用上面的ip和端口,否则默认为proxy_pass的IP和端口
		  proxy_set_header X-Forwarded-Proto  $scheme; # 使用上面的https scheme
    proxy_set_header X-Forwarded-Uri  $request_uri;
    proxy_set_header X-Real-IP        $remote_addr; # 访问的真实地址
    proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for; # X-Forwarded-For头信息可以有多个,中间用逗号分隔,第一项为真实的客户端ip,剩下的就是曾经经过的代理或负载均衡的ip地址,经过几个就会出现几个。
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://patrol-gateway:8301/;
  }

  localtion /web {
    root html
    index  index.html index.htm;
  }

} } ```

nginx动态代理配置

工作中经常遇到需要在前端访问第三方平台接口的情况,前端直接访问会遇到跨域、http 禁止调用 https 等问题,故需要在后台通过 Nginx 进行反向代理。随着第三方平台的增加,反向代理配置文件越来越复杂,因此笔者在考虑通过参数传递目标地址实现动态反向代理,本文将详细介绍实现过程。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# map 指令根据客户端请求头中 $http_upgrade 的值构建 $connection_upgrade 的值;如果 $http_upgrade 没有匹配,默认值为 upgrade,如果 $http_upgrade 配置空字符串,值为 close
#map $http_upgrade $connection_upgrade {
#    default upgrade;
#    '' close;
#}

location /_proxy/ {
    # 配置 DNS 服务器,proxy_pass 采用变量时需要指定
    resolver 114.114.114.114 valid=3600s;

    # 通过正则截取路由中的 sub url
    if ($request_uri ~* "/_proxy/(.*)") {
        set $proxy_url $1;
    }

    # 解析请求地址,并进行反向代理
    set $is_matched 0;
    #if ($proxy_url ~* "^(http|ws)(s?):\/\/?([a-zA-Z0-9\-\.]+:?\d*)([^\?]*)") {
    if ($proxy_url ~* "^(http)(s?):\/\/?([a-zA-Z0-9\-\.]+:?\d*)([^\?]*)") {
        set $is_matched 1;
        set $proxy_protocol http$2;
        set $proxy_host $3;
        set $proxy_uri $4;
        set $proxy_url $proxy_protocol://$proxy_host$proxy_uri;

        proxy_pass $proxy_url$is_args$args;
    }


    # 请求服务器升级协议为 WebSocket
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    #proxy_set_header Connection $connection_upgrade;

    # 设置读写超时时间,默认 60s 无数据连接将会断开
    proxy_read_timeout 300s;
    proxy_send_timeout 300s;

    # Host 主机名,为了避免目标服务做限制此处采用目标地址的 Host
    proxy_set_header Host $proxy_host;
    # X-Real-IP 将真实访问者的远端 IP 地址转发给代理服务器
    proxy_set_header X-Real-IP $remote_addr;
    # X-Forwarded-For 标记客户端通过代理连接到服务器的源 IP
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    # X-Forwarded-Host 标记客户端通过代理连接到服务器的原始主机
    proxy_set_header X-Forwarded-Host $host:$server_port;
    # X-Forwarded-Server 代理服务器的主机名
    proxy_set_header X-Forwarded-Server $host;
    # X-Forwarded-Port 定义客户端请求的原始端口
    proxy_set_header X-Forwarded-Port $server_port;
    # X-Forwarded-Proto 标记客户端通过代理连接到服务器的协议
    proxy_set_header X-Forwarded-Proto $scheme;
    # proxy_set_header X-Forwarded-Proto $proxy_x_forwarded_proto;

    # 如果目标地址为非 http、https、ws、wss 请求,提示错误信息
    default_type application/json;
    if ($is_matched = 0) {
        return 200 '{"code": 404, "message": "The proxy url is invalid!", "proxy_url": $proxy_url}';
    }
    # 调试输出
    # return 200 '{"code": 200, "proxy_url": $proxy_url$is_args$args, "proxy_host": $proxy_host, "request_uri": $request_uri}';
}

版权声明:本文为CSDN博主「Hit不死的小强」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/qq_44797987/article/details/127818406