NGINX wildcard rewrite in same server block

﹥>﹥吖頭↗ 提交于 2019-12-13 09:01:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!