我有两个域website1.com
和website2.com
链接到我的服务器。
我正在尝试执行以下重写规则:
http://website1.com/ --> /website1/ (static)
http://website2.com/ --> /website2/ (static)
http://website1.com/app/ --> http://localhost:8080/web-app/web1/
http://website2.com/app/ --> http://localhost:8080/web-app/web2/
根据网址,用户将被重定向到由nginx或应用服务器提供服务的静态网站。
这是我到目前为止所尝试的内容:
location / {
root html;
index index.html index.htm;
if ($http_host = website1.com) {
rewrite / /website1/index.html break;
rewrite (.*) /website1/$1;
}
if ($http_host = website2.com) {
#same logic
}
}
location /app/ {
proxy_pass http://localhost:8080/web-app/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
if ($http_host = website1.com) {
rewrite /app/(.*) /$1 break;
rewrite /app /index.html;
}
if ($http_host = website2.com) {
#same logic
}
}
静态部分似乎工作正常,但无论请求的文件是什么,重定向Web应用程序部分似乎都提供index.html。
答案 0 :(得分:1)
这不是一个明确的答案,而只是我对如何使nginx代理工作的解释。
root html;
index index.html index.htm;
server {
listen 80;
server_name website1.com;
location / {
alias html/website1;
}
location /app/ {
proxy_pass http://localhost:8080/web-app/web1/
}
}
server {
listen 80;
server_name website2.com;
location / {
alias html/website2;
}
location /app/ {
proxy_pass http://localhost:8080/web-app/web2/
}
}
问题似乎是由这些重写造成的:
rewrite /app/(.*) /$1 break;
rewrite /app /index.html;
使用具有server_name
和alias
指令的服务器块,我们可以省去需要使用那么多逻辑。如果有任何事情尚不清楚,请告诉我。
答案 1 :(得分:1)
我认为你做错了。 如果主机之间存在很大的差异,那么拥有两个不同的配置会更清晰,更高效对于每个主持人。
另一方面,如果您打算使用多个几乎相同的配置,那么正确的方法可能是map
,而不是if
。
回到你的配置 - 我试过运行它只是为了看它是如何工作的,你可能会注意到的一件事是proxy_pass
中指定的路径在$host
后有效地成为noop在相同的上下文中涉及更改rewrite
的特定$uri
- 这是设计的,并且在http://nginx.org/r/proxy_pass(“当URI更改时非常清楚地记录使用重写指令“)在代理位置内。
因此,事实上,使用以下配置似乎符合您的规范:
%curl -H "Host: host1.example.com" "localhost:4935/app/"
host1.example.com/web-app/web1/
%curl -H "Host: host2.example.com" "localhost:4935/app/"
host2.example.com/web-app/web2/
%curl -H "Host: example.com" "localhost:4935/app/"
example.com/web-app/
这是我用过的配置:
server {
listen [::]:4935;
default_type text/plain;
location / {
return 200 howdy;
}
location /app/ {
proxy_set_header Host $host;
proxy_pass http://localhost:4936/web-app/;#path is NOOP if $uri get changed
if ($host = host1.example.com) {
rewrite /app/(.*) /web-app/web1/$1 break;
rewrite /app /web-app/index.html;
}
if ($host = host2.example.com) {
rewrite /app/(.*) /web-app/web2/$1 break;
rewrite /app /web-app/index.html;
}
}
}
server {
listen [::]:4936;
return 200 $host$request_uri\n;
}