nginx 作为微服务的前端—反向代理简答配置例程 (/etc/nginx/nginx.conf):
正向代理可以隐藏真实的客户端, 反向代理可以隐藏真实的服务器.
worker_processes auto;
worker_rlimit_nofile 100000;
pid /run/nginx.pid;
events {
worker_connections 4096;
use epoll;
multi_accept on;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_user_agent" $request_time|$upstream_response_time - x_forwared_for: "$http_x_forwarded_for"';
ssl_session_cache shared:SSL:20m;
ssl_session_timeout 15m;
proxy_cache off;
send_timeout 5;
keepalive_timeout 30;
upstream my_backend {
server 127.0.0.1:7081;
server 127.0.0.1:7082;
}
server {
server_name *.my_domain.com;
access_log /var/log/nginx/access.log main buffer=256k flush=10s;;
listen 7080 ssl;
location / {
proxy_pass https://my_backend;
# proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
auth_basic "user";
auth_basic_user_file /opt/nginx/.htpasswd;
}
ssl_certificate /etc/ssh/xxx.pem;
ssl_certificate_key /etc/ssh/xxx.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
}
# default server
server {
listen 7080 ssl default_server;
server_name _;
ssl_certificate /etc/ssh/xxx.pem;
ssl_certificate_key /etc/ssh/xxx.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers HIGH:!aNULL:!MD5;
default_type application/json;
return 403 '{}';
}
}
注意:
- 每一个nginx子进程的 worker_connections 包含连接的 in+out, 所以对应的最大连接数需要除以 2;
- 自定义 log_format是为了记录客户端的接入ip , 使用 header 中
X-Forwarded-For
字段,并且优化日志写入方式 - 加上default server是为了将 header 中
Host
字段不是*.my_domain.com
的直接返回403 error. nginx -s reload
中心加载配置文件(nginx docker 可以自动检测配置文件修改然后加载)nginx -t
测试配置文件是否有错误
nginx 生成自签名证书:
openssl genrsa -out server.key 2048
openssl rsa -in server.key -out server.key
openssl req -sha256 -new -key server.key -out server.csr -subj '/CN=localhost'
openssl x509 -req -sha256 -days 365 -in server.csr -signkey server.key -out server.crt
将公私钥合成 .pem 文件:
cat server.crt server.key > server.pem
nginx 配置 ssl 证书:
ssl_certificate /etc/ssh/server.pem;
ssl_certificate_key /etc/ssh/server.key;
ref link:
- NGINX tuning: https://gist.github.com/denji/8359866
- https://stackoverflow.com/questions/54136265/nginx-reverse-proxy-disable-cache