七仔的博客

七仔的博客GithubPages分博

0%

Nginx的配置使用

https的配置、强制使用https访问、开启GZIP、location的判断、开启缓存

Nginx的配置使用

https的配置

首先去申请一个ssl证书并下载相关的文件:pem和key

然后配置443端口转发到相应的端口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# HTTPS server
# https访问
server {
listen 443 ssl;
server_name 你的域名;
ssl on;
root html;
index index.html index.htm;

ssl_certificate pem地址;
ssl_certificate_key key地址;

ssl_session_timeout 5m;

ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;

location / {
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_pass 转发地址如http://127.0.0.1:8003;
}
}

强制使用https访问

就是如果访问端口是http就重定向到https,这里强制80端口使用https访问

1
2
3
4
5
6
7
# HTTP server
# 重定向到https
server {
listen 80;
server_name 你的域名;
return 301 https://$server_name$request_uri;
}

开启GZIP

在http区块下添加如下代码

1
2
3
4
5
6
7
8
9
10
11
12
#开启gzip
gzip on;
#低于1kb的资源不压缩
gzip_min_length 1k;
#压缩级别【1-9】,越大压缩率越高,同时消耗cpu资源也越多,建议设置在4左右。
gzip_comp_level 4;
#需要压缩哪些响应类型的资源,多个空格隔开。
gzip_types text/plain application/javascript application/x-javascript text/javascript text/xml text/css;
#配置禁用gzip条件,支持正则。此处表示ie6及以下不启用gzip(因为ie低>版本不支持)
gzip_disable "MSIE [1-6]\.";
#是否添加“Vary: Accept-Encoding”响应头
gzip_vary on;

区分爬虫进行转发

在location区块下添加如下代码

1
2
3
if ($http_user_agent ~* "Baiduspider|twitterbot|facebookexternalhit|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator|bingbot|Sosospider|Sogou Pic Spider|Googlebot|360Spider") {
proxy_pass 要转发的地址;
}

location的判断

判断文件

1
location ~* .jpg|.png|.gif|.jpeg|.html|.js|.css|.ico$ {}

判断服务

1
location ~* ^/(auth|admin|code|gen|actuator|monitor|mp|daemon|job|tx|pay|act|blog) {}

开启缓存

1
2
3
4
5
6
7
8
proxy_cache_path 本地缓存路径 levels=1:2 keys_zone=cachedata:10m max_size=10g inactive=60m use_temp_path=off;
server {
  # ...
  location / {
    proxy_cache cachedata;
    proxy_pass 要转发的地址;
  }
}

此为博主副博客,留言请去主博客,转载请注明出处:https://www.baby7blog.com/myBlog/47.html

欢迎关注我的其它发布渠道