Loading...

nginx常用配置

日常推荐2个月前更新 Jone
58 0 0

总结一下nginx使用心得和一些常用配置解释与建议值。

常用参数

worker-process

工作线程数,默认下为1。

建议把值改成auto,能够根据机器cpu核心数自动配置最优值。

1
worker_processes  auto;

worker_connections

用来设置每一个工作线程数同时支持的最大连接数,默认值是1024。

1
worker_connections  1024;

可以根据服务器内存大小进行更改。

反代配置

1
2
3
4
5
6
7
8
9
10
11
12
13
upstream http_backend {
server 127.0.0.1:8081;

keepalive 16; #设置长连接超时时间
}
location ^~ /api/ {
proxy_pass http://http_backend/;
proxy_http_version 1.1;
proxy_set_header Connection ""; # 禁用"Connection"头
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

此配置可以与后端接口保持长连接,可以把后端接口请求反代到服务器8081端口。

常用location配置

一. location匹配路径末尾没有 /
此时proxy_pass后面的路径必须和location设置的路径一致:

1
2
3
4
5
6
7
8
location /index
{
proxy_redirect off;
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_pass http://localhost:8080/index;
}

外面访问:http://romotehost/index/index.html
相当于访问:http://localhost:8080/index/index.html

二. location匹配路径末尾有 /
此时proxy_pass后面的路径需要分为以下四种情况讨论:

proxy_pass后面的路径只有域名且最后没有 /:

外面访问:http://romotehost/index/index.html
相当于访问:http://localhost:8080/index/index.html

1
2
3
4
5
6
7
8
location /index/
{
proxy_redirect off;
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_pass http://localhost:8080;
}

外面访问:http://romotehost/index/index.html
相当于访问:http://localhost:8080/index/index.html

proxy_pass后面的路径只有域名同时最后有 /:

外面访问:http://romotehost/index/index.html
相当于访问:http://localhost:8080/index.html

1
2
3
4
5
6
7
8
location /index/
{
proxy_redirect off;
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_pass http://localhost:8080/;
}

外面访问:http://romotehost/index/index.html
相当于访问:http://localhost:8080/index.html

proxy_pass后面的路径还有其他路径但是最后没有 /:

外面访问:http://romotehost/index/index.html
相当于访问:http://localhost:8080/testindex.html

1
2
3
4
5
6
7
8
location /index/
{
proxy_redirect off;
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_pass http://localhost:8080/test;
}

外面访问:http://romotehost/index/index.html
相当于访问:http://localhost:8080/testindex.html

proxy_pass后面的路径还有其他路径同时最后有 /:

外面访问:http://romotehost/index/index.html
相当于访问:http://localhost:8080/index/index.html

1
2
3
4
5
6
7
8
location /index/
{
proxy_redirect off;
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_pass http://localhost:8080/test/;
}

外面访问:http://romotehost/index/index.html
相当于访问:http://localhost:8080/index/index.html

借鉴于:nginx 反向代理location路径设置_nginx location proxy set_码农小非的博客-CSDN博客

© 版权声明

相关文章