0

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;   
}
breebee2
  • 23
  • 1

1 Answers1

0

Take a look at the docs:


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.

cnst
  • 25,870
  • 6
  • 90
  • 122
  • The above works perfect, i tried to change it a rewrite instead of a return so that i dont get ssl certificate not valid for subdomain. Is there a way to bypass this issue? – breebee2 Jul 28 '17 at 13:27
  • I don't think you should be using rewrite here (if you need the request URI, use `$request_uri`); but there's no difference either way for SSL; you obviously have to have proper certs for all subdomains for this to work without a warning (or just don't use SSL!). – cnst Jul 28 '17 at 18:32