Skip to main content
 首页 » 编程设计

nginx之Nginx将子域转换为路径组件而无需重定向

2024年09月07日13mayingbao

这个想法是将传入请求接收到http://abc.example.com/...并将其重写为http://example.com/abc/...
使用301/302重定向很容易做到:

# rewrite via 301 Moved Permanently 
server { 
  listen 80; 
  server_name abc.example.com; 
  rewrite ^ $scheme://example.com/abc$request_uri permanent; 
} 

诀窍是当 abc.example.comexample.com指向同一Nginx实例时,将URL透明更改为客户端的

换句话说,Nginx是否可以在请求example.com/abc/...时提供abc.example.com/...中的内容,而无需其他客户端往返

起点配置

使用301完成任务的Nginx配置:
# abc.example.com 
server { 
  listen 80; 
  server_name abc.example.com; 
  rewrite ^ $scheme://example.com/abc$request_uri permanent; 
} 
 
# example.com 
server { 
  listen 80; 
  server_name example.com; 
  location / {  
    # ... 
  } 
} 

请您参考如下方法:

# abc.example.com 
server { 
  listen 80; 
  server_name abc.example.com; 
  location / { 
    proxy_pass http://127.0.0.1/abc$request_uri; 
    proxy_set_header Host example.com; 
  } 
}