问题
I cannot find an example of the specific rewrite rule im attempting.
I would like to have a rewrite rule for only subdomains entered for example.
https://sub.example.com/ -> https://example.com/directory1/directory2/sub
From what ive been trying this looks like the closest code i have got.
server_name example.com;
if ($host = *.example.com)
return 301 https://example.com/directory1/directory2/$1;
}
回答1:
Take a look at the docs:
- http://nginx.org/r/server_name
- http://nginx.org/r/if
This would be one solution:
server_name .example.com;
if ($host ~ ^(?<sub>.+)\.example\.com$) {
return 301 http://example.com/directory1/directory2/$sub;
}
This would be another solution:
server_name ~^(?<sub>.+)\.example\.com$;
return 301 http://example.com/directory1/directory2/$sub;
Which solution is better? It's hard to tell — it depends on the patterns of the traffic you receive, as well as on what other servers are configured on the same listen handle.
来源:https://stackoverflow.com/questions/45357325/nginx-wildcard-rewrite-in-same-server-block