简体   繁体   中英

Virtual host or simply rewrite?

I've a website that has a profile page. Obviously all users have an own profile page available on this url: domain.dev/profile?user=%username%.

Now, I want to do that every user can see the profile on username.domain.dev.

I saw many post about that like How to let PHP to create subdomain automatically for each user? but it doesn't resolve my problem.

I've my website on ubuntu (nginx) and also on Windows IIS 10. How can I do that? Do you have some other link/question that can I see? Or some suggestion?

In Nginx, you just need to set up something similar to this:

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

Notice the:

server_name  *.domain.dev;

Within your application, you will need to split/handle the HOST header.

Another approach but this implies a redirect 301 is to do something like this:

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

In this case, notice the regex in the server_name:

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

This helps you to use the subdomain as $subdomain .

To avoid a redirect this may work:

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; 
  } 
}

For testing purposes, I am using http://httpbin.org/ on the proxy_pass`, so that you could test with something like:

$ 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"
}

Notice the response:

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

Matching the subdomain foo .your-domain.tld in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM