![如何使用 nginx 和 proxy_pass 创建子域名](https://linux22.com/image/686793/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8%20nginx%20%E5%92%8C%20proxy_pass%20%E5%88%9B%E5%BB%BA%E5%AD%90%E5%9F%9F%E5%90%8D.png)
我目前已在 为我的服务器设置了 nginx my.server.com
。使用当前配置,我可以使用http://my.server.com/app1
或访问不同的应用程序http://my.server.com/app2
。
我有一个apps.conf
放置在/etc/nginx/sites-enabled/
此的是它的样子:
upstream app1_servers {
server 172.12.11.10:8080;
}
upstream app2_servers{
server 172.12.11.10:9090;
}
server {
listen 80;
server_name my.server.com;
return 301 https://my.server.com/$request_uri; #force https
}
server {
listen 443;
ssl on;
ssl_certificate /etc/ssl/my.server.com/cert.pem;
ssl_certificate_key /etc/ssl/my.server.com/priv.pem;
server_name my.server.com;
location /app1 {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-Proto https;
proxy_pass http://app1_servers/app1;
proxy_redirect http://$host https://$host;
proxy_set_header Host $host;
}
location /app2 {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-Proto https;
proxy_pass http://app2_servers/app2;
proxy_redirect http://$host https://$host;
proxy_set_header Host $host;
}
}
问题
上面的方法很好用。但是,现在我想改变访问app1
和的方式app2
。我想通过http://app1.my.server.com
和访问它们http://app2.my.server.com
,同时仍然保持强制 SSL 并执行proxy_pass
我需要进行哪些配置更改才能使其生效?此外,我想将每个应用程序的配置设置保存在其单独的文件中。
答案1
这应该相当简单。你只需要为每个子域创建服务器块,为子域获取 SSL 证书(除非主证书是通配符证书),然后复制适用的位置块并进行一些调整。
类似这样的事情应该可以工作,尽管我还没有测试过,所以几乎肯定需要进行一些调整。
server {
listen 80;
server_name app1.server.com;
return 301 https://app1.server.com/$request_uri; #force https
}
server {
listen 443;
ssl on;
ssl_certificate /etc/ssl/app1.server.com/cert.pem; # changed
ssl_certificate_key /etc/ssl/app1.server.com/priv.pem; # changed
server_name app1.server.com; # changed
location / { # changed
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Server $host;
proxy_set_header X-Forwarded-Proto https;
proxy_pass http://app1_servers/app1;
proxy_redirect http://$host https://$host;
proxy_set_header Host $host;
}