我有一个在端口 3000 上运行的多租户应用程序,该应用程序将动态加载并生成各种网站的内容,例如localhost:3000/webiste1.com/home
, localhost:3000/webiste2.com/contacts
等等。
当然,我希望从 访问 website1,webiste1.com
而不仅仅是从localhost:3000/webiste1.com
。
基本上,我需要webiste1.com
能够提供内容的localhost:3000/webiste1.com/
网站不是静态的,因此进行一些重写是不够的,因此我尝试使用proxy_pass
:
第一次尝试 :
server {
server_name webiste1.com;
location ~ ^/_next {
proxy_pass http://127.0.0.1:3889;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location ~ ^(.*)$ {
proxy_pass http://127.0.0.1:3889/$host$request_uri; <--adding a slash at the end cause infinite loop
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/webiste1.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/webiste1.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = webiste1.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
server_name webiste1.com;
listen 80;
return 404; # managed by Certbot
}
如果我访问 webiste1.com,它会重定向到 webiste1.com/webiste1.com
第二次尝试 :
server {
server_name webiste1.com;
location ~ ^/_next {
proxy_pass http://127.0.0.1:3889;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
location ~ ^(.*)$ {
proxy_pass http://127.0.0.1:3889/$host; <-- try to pass $host only
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
如果我访问 website1.com,它似乎可以工作,内容来自localhost:3000/website1.com
,但是如果我访问website1.com./some/path
代理,它仍然提供来自 的内容localhost:3000/website1.com
,而它应该提供来自 的内容localhost:3000/website1.com/some/path
。我怎样才能使它成为webistes1.com/any/path
来自 的代理localhost:3000/website1.com/any/path
?
谢谢
答案1
问题是该proxy_pass
目的地在您的第二个配置中是固定的。
这种方法应该有效:
server {
server_name example.com;
location / {
proxy_pass http://127.0.0.1:3889/$host/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
正如所述proxy_pass 文档,这里nginx将 中指定的规范化请求URI部分替换location
为 中指定的URI proxy_pass
。
也就是说,在这种情况下,URLhttps://example.com/
被转换为http://127.0.0.1:3889/example.com/
。
并https://example.com/123/
翻译为http://127.0.0.1:3889/example.com/123
。