这是一个相当简单的问题:如何重定向到另一个域并仍然转发子域?示例:http://foo.domainone.com/bar.php->http://foo.domaintwo.com/bar.php
提前致谢!
答案1
下面的命令应该对你有用(这会将 test.com 重定向到 abc.com):
server {
# Listen on ipv4 and ipv6 for requests
listen 80;
listen [::]:80;
# Listen for requests on all subdomains and the naked domain
server_name test.com *.test.com;
# Check if this is a subdomain request rather than on the naked domain
if ($http_host ~ (.*)\.test\.com) {
# Yank the subdomain from the regex match above
set $subdomain $1;
# Handle the subdomain redirect
rewrite ^ http://$subdomain.abc.com$request_uri permanent;
break;
}
# Handle the naked domain redirect
rewrite ^ http://abc.com$request_uri permanent;
}
这应确保裸域和任何子域(或子、子域)都重定向到新的“基础”域。实践中有几个例子:
phoenix:~ damian$ curl -I -H "Host: test.com" web1-france
HTTP/1.1 301 Moved Permanently
Server: nginx/1.1.1
Date: Sat, 08 Oct 2011 06:43:45 GMT
Content-Type: text/html
Content-Length: 160
Connection: keep-alive
Location: http://abc.com/
phoenix:~ damian$ curl -I -H "Host: subdomain1.test.com" web1-france
HTTP/1.1 301 Moved Permanently
Server: nginx/1.1.1
Date: Sat, 08 Oct 2011 06:43:50 GMT
Content-Type: text/html
Content-Length: 160
Connection: keep-alive
Location: http://subdomain1.abc.com/
phoenix:~ damian$ curl -I -H "Host: wibble.subdomain1.test.com" web1-france
HTTP/1.1 301 Moved Permanently
Server: nginx/1.1.1
Date: Sat, 08 Oct 2011 06:43:55 GMT
Content-Type: text/html
Content-Length: 160
Connection: keep-alive
Location: http://wibble.subdomain1.abc.com/
在重写行中,您可以指定“last”而不是“permanent”,以获得 302 Moved Temporarily 而不是 301 Moved Permanently。如果您要移动域名,则应该选择后者 :)
希望这可以帮助。
答案2
在我自己的服务器上进行测试,应该很容易适应你的服务器:
server {
listen 80;
server_name test.shishnet.org;
root /var/www;
if ($http_host ~ (.*)\.shishnet\.org) {
set $subdomain $1;
rewrite (.*)$ http://$subdomain.example.com$1;
}
}
答案3
在这里扩展 Damian 但修复重复的查询参数:
server {
# Listen for requests on all subdomains and the naked domain
server_name _;
# Check if this is a subdomain request rather than on the naked domain
if ($http_host ~ (.*)\.example\.com) {
# Yank the subdomain from the regex match above
set $subdomain $1;
# Handle the subdomain redirect
rewrite ^ http://$subdomain.example.com$request_uri? permanent;
break;
}
# Handle the naked domain redirect
rewrite ^ http://example.com$request_uri? permanent;
}
也可以看看: