nginx proxy_pass同时支持http/https的小技巧
个人学习笔记,谢绝转载!!!
原文:https://www.cnblogs.com/wshenjin/p/13183929.html
nginx在配置http/https代理,最开始比较麻烦的写法:
upstream example
{
server 1.1.1.1:80;
server 2.2.2.2:80 backup;
}
upstream example_https
{
server 1.1.1.1:443;
server 2.2.2.2:443 backup;
}
server
{
listen 80;
server_name www.example.com;
index index.html index.htm index.php;
root /data/web/webclose;
location / {
proxy_pass http://example;
expires off;
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;
}
access_log /data/logs/$host.log access;
}
server
{
listen 443 ssl;
server_name www.example.com;
root /data/web/webclose;
include ssl_example.conf;
location / {
proxy_pass https://example_https;
expires off;
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;
}
access_log /data/logs/$host.log access;
}
这种写法比较麻烦,要写两份。
因此投机取巧换个写法:
upstream example_http
{
server 1.1.1.1:80;
server 2.2.2.2:80 backup;
}
upstream example_https
{
server 1.1.1.1:443;
server 2.2.2.2:443 backup;
}
server
{
listen 80;
listen 443 ssl;
server_name www.example.com;
index index.html index.htm index.php;
root /data/web/webclose;
include ssl_example.conf;
location / {
proxy_pass $scheme://example_$scheme;
expires off;
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;
}
access_log /data/logs/$host.log access;
}
可以充分利用nginx的变量简化配置的编写。