在Nginx中,如何重写API/proxy的子域

分享于 

3分钟阅读

互联网

  繁體

问题:

我有一个设置,其中未知数量的公司可以创建company.app.com


server {


 listen 443 ssl http2;


 listen [::]:443 ssl http2;


 ssl on;


 ssl_certificate /etc/ssl/certs/cert.pem;


 ssl_certificate_key /etc/ssl/private/key.pem;



 server_name ????.app.com; <-- How?



 charset utf-8;



 location / {


 proxy_pass http://0.0.0.0:5000;


 proxy_http_version 1.1;


 proxy_set_header Connection "";


 proxy_connect_timeout 300;


 proxy_send_timeout 300;


 proxy_read_timeout 300;


 send_timeout 300; 


 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_set_header X-Forwarded-Host $server_name;


 }


}




答案1:

可以将部分Host头/TLS SNI字段捕获到server_name中的变量中,如下所示:


server_name ~^(?<company>.+).app.com;



稍后,变量可以在proxy_pass 目标中使用:


proxy_pass http://192.168.100.100:5000/$company/;




答案2:

由于Nginx支持通配符,它应该类似于:


server {


listen 443 ssl http2;


listen [::]:443 ssl http2;


ssl on;


ssl_certificate /etc/ssl/certs/cert.pem;


ssl_certificate_key /etc/ssl/private/key.pem;



server_name *.app.com;



charset utf-8;



location / {


 proxy_pass http://0.0.0.0:5000;


 proxy_http_version 1.1;


 proxy_set_header Connection "";


 proxy_connect_timeout 300;


 proxy_send_timeout 300;


 proxy_read_timeout 300;


 send_timeout 300; 


 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_set_header X-Forwarded-Host $server_name;


}


}




server {


listen 443 ssl http2;


listen [::]:443 ssl http2;


ssl on;


ssl_certificate /etc/ssl/certs/cert.pem;


ssl_certificate_key /etc/ssl/private/key.pem;



server_name *corp.app.com;



charset utf-8;



location / {


 proxy_pass http://0.0.0.0:5000;


 proxy_http_version 1.1;


 proxy_set_header Connection "";


 proxy_connect_timeout 300;


 proxy_send_timeout 300;


 proxy_read_timeout 300;


 send_timeout 300; 


 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_set_header X-Forwarded-Host $server_name;


}


}



两者都有效。



API  Virtual  Nginx  路径  重写  子域  
相关文章