Nginx相关配置

Nginx 相关配置

修改默认用户

1
2
修改 nginx.conf 中 `user nginx;`,默认用户为 nobody
构建 nginx 时添加参数 `--user=nginx --group=nginx`

修改工作进程

1
2
3
4
5
6
7
8
9
10
# 工作进程数,一般是 CPU 核心数,设置成 auto 也可
worker_processes 4;
# 工作进程的最大打开文件限制,太小会出现 `Too many open files`,此参数受系统文件的最大打开数限制,通过 `cat /proc/sys/fs/file-max` 查看,使用 `ulimit -n` 修改文件系统最大打开数
worker_rlimit_nofile 10240;
event {
# 每个工作进程对应的连接数
worker_connections 1024;
# 使用 epoll 的 I/O 多路复用模型
use epoll;
}

长连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
http {
# 与浏览器的长连接时间
keepalived_timeout 65;

upstream server_pool {
server localhost:8080 weight=1 max_fails=2 fail_timeout=30s;
server localhost:8081 weight=1 max_fails=2 fail_timeout=30s;
# 与服务器的长连接数
keepalive 300;
}
location / {
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_pass http://server_pool/;
}
}

高效传输

1
2
3
4
# 减少文件在应用和内核之间拷贝
sendfile on;
# 当数据包达到一定大小再发送
tcp_nopush on;

压缩

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
http {
# 开启压缩
gzip on;
# 压缩的 http 协议版本
gzip_http version 1.1;
# 压缩级别,1-9,级别越大 CPU 使用越高
gzip_comp_level 6;
# 限制最小压缩,小于 1k 文件不会压缩
gzip_min_length 1k;
# gzip 申请内存的大小,按块大小的倍数申请内存空间
gzip_buffers 4 16k;
# IE6 及以下版本不启用bvbvzip
gzip disable "MSIE [1-6]\.";
# 需要压缩的类型
gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php application/javascript application/json;
# 启用应答头 Vary: Accept-Encoding
gzip_vary on;
gzip_proxied any;
}

缓存

1
2
3
4
5
6
7
http {
location ~* \.(ico|jpe?g|gif|png|bmp|swf|flv)$ {
# 过期时间
expires 12h;
# expires @22h30m;
}
}

防盗链

1
2
3
4
5
6
7
8
9
10
11
http {
server {
location ~* \.(gif|jpg|png|swf|flv)$ {
root /data/www/images/;
valid_referers *.ckx.ink;
if ($invalid_referer) {
return 404;
}
}
}
}

跨域

1
2
3
4
5
6
7
8
9
10
11
12
http {
server {
# 允许跨域请求的域,* 代表所有
add_header 'Access-Control-Allow-Origin' *;
# 允许带上 cookie 请求
add_header 'Access-Control-Allow-Credentials' 'true';
# 允许请求的方法,比如 GET/POST/PUT/DELETE
add_header 'Access-Control-Allow-Methods' *;
# 允许请求的 header
add_header 'Access-Control-Allow-Headers' *;
}
}

location 匹配规则

1
2
3
4
5
空格:默认匹配,普通匹配
=:精确匹配
~*:匹配正则表达式,不区分大小写
~:匹配正则表达式,区分大小写
^~:以某个字符路径开头

https

安装 ssl 模块:http_ssl_module

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
http {
server {
#SSL 访问端口号为 443
listen 443 ssl;
#填写绑定证书的域名
server_name ckx.ink;
#证书文件名称
ssl_certificate /etc/tencentssl/1_ckx.ink_bundle.crt;
#私钥文件名称
ssl_certificate_key /etc/tencentssl/2_ckx.ink.key;
ssl_session_timeout 5m;
#请按照以下协议配置
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
#请按照以下套件配置,配置加密套件,写法遵循 openssl 标准。
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;
ssl_prefer_server_ciphers on;
#HSTS
add_header Strict-Transport-Security "max-age=31536000";
}
}