问题原文
原帖链接 · Jake · CC BY-SA 3.0
Say i have multiple variations on a domain name, one brandname registered at multiple top-level domains; and they all need to go to one specific domain + append a dedicated custom uri that relates to the originally requested domain.
For example i have:
- domain.tld
- domain.net
- domain.org
- domain.com
Where domain.com is the one where all requests need to land after appending an extra uri like this:
- domain.com/tld
- domain.com/net
- domain.com/org
I came up with this working setup:
# (www.)domain.tld
server {
listen 80;
server_name domain.tld www.domain.tld;
return 301 $scheme://www.domain.com/tld$request_uri;
}
# (www.)domain.net
server {
listen 80;
server_name domain.net www.domain.net;
return 301 $scheme://www.domain.com/net$request_uri;
}
# (www.)domain.org
server {
listen 80;
server_name domain.org www.domain.org;
return 301 $scheme://www.domain.com/org$request_uri;
}
# (www.)domain.com
server {
listen 80;
server_name domain.org www.domain.org;
location / {
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://backend.host:port;
}
}
But the declaration of multiple server blocks, although logical, looks over-verbose.
TL;DR Are there ways to accomplish this kind of redirecting without having to define a server block for each domain?
已采纳解答
原帖链接 · Richard Smith · CC BY-SA 3.0
A regular expression server_name directive can capture the last element of the domain name for use in the redirect. For example:
server {
listen 80;
server_name ~\.(?<tld>[^.]+)$;
return 301 $scheme://www.domain.com/$tld$request_uri;
}
See this document for details.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
