虚拟主机还是只是重写?

时间:2017-09-15 19:00:20

标签: nginx virtualhost

我的网站上有个人资料页面。显然,所有用户在此网址上都有自己的个人资料页面:domain.dev/profile?user=%username%。

现在,我希望每个用户都能看到username.domain.dev上的个人资料。

我看过很多关于How to let PHP to create subdomain automatically for each user?的帖子,但它并没有解决我的问题。

我的网站是ubuntu(nginx)以及Windows IIS 10。 我怎样才能做到这一点?你有其他一些我能看到的链接/问题吗?或者一些建议?

1 个答案:

答案 0 :(得分:0)

在Nginx中,你只需要设置类似的东西:

server {
    listen       80;
    server_name  *.domain.dev;
    ...
}

请注意:

server_name  *.domain.dev;

在您的应用程序中,您需要拆分/处理HOST标题。

另一种方法,但这意味着redirect 301要做这样的事情:

server {
   listen      80;
   server_name ~^(?<subdomain>\w+)\.your-domain\.tld$;
   return 301 https://domain.dev/profile?user=$subdomain;
}

在这种情况下,请注意server_name中的regex

server_name ~^(?<subdomain>\w+)\.your-domain\.tld$;

这有助于您将子域用作$subdomain

为避免重定向,这可能有效:

server {
  listen      80;
  server_name ~^(?<subdomain>\w+)\.your-domain\.tld$;

  location / {
    resolver 8.8.8.8;
    proxy_pass http://httpbin.org/get?user=$subdomain;
    proxy_set_header Host httpbin.org; 
  } 
}

出于测试目的,我使用的是http://httpbin.org/ on the proxy_pass`,因此您可以使用以下内容进行测试:

$ curl foo.your-domain.tld:8080
{
  "args": {
    "user": "foo"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Connection": "close", 
    "Host": "httpbin.org", 
    "User-Agent": "curl/7.54.0"
  }, 
  "origin": "91.65.17.142", 
  "url": "http://httpbin.org/get?user=foo"
}

注意回复:

"url": "http://httpbin.org/get?user=foo"

在这种情况下匹配子域名foo。your-domain.tld。

相关问题