0

Im building a platform, where the main domain is example.com. The server is using CentOS 7 with Apache 2.

My users' URL will be username.example.com, which actually loads the contents from example.com/username, so that:

  • mjohnson.example.com loads the contents from example.com/mjohnson
  • mjohnson.example.com/about loads the contents from example.com/mjohnson/about
  • jsmith.example.com/ loads the contents from example.com/jsmith/

etc. What would be the best approach for this setup? I have full access to the httpd.conf configuration file.

4
  • 1
    Did you try Dynamically Configured Mass Virtual Hosting httpd.apache.org/docs/2.4/vhosts/mass.html ? Oct 7, 2019 at 20:44
  • @NikitaKipriyanov This looks good, but i'm afraid the httpd.conf file will get too big when the platform has too many users. Is there any way to achieve this with some kind of wildcard?
    – Andres SK
    Oct 7, 2019 at 21:27
  • 1
    Did you actually read the article? It's exactly about that. Oct 8, 2019 at 2:42
  • That is the way to only write ~10 lines into config and support any number of per-user vhosts. Please, read an article. Also, this solution is much more clean and efficient than mod_rewrite suggested in the answer (Apache developers clearly discourage using mod_rewrite in their manuals). Oct 8, 2019 at 5:29

1 Answer 1

0

It's very simple using mod_rewrite for the simple case.

RewriteEngine on
RewriteCond "%{HTTP_HOST}" "^([^.]+)\.example\.com$" [NC,NV]
RewriteRule "^(.*)$" "%{REQUEST_SCHEME}://%{HTTP_HOST}/%1$1" [L]

Getting Your 1st point is not possible as You can never request just the hostname.
If You type it like that, in the browser or the client it gets always the / appended as the HTTP protocol requires some URI to request from the server which cannot be the empty string.

Depending on You exact requirements it can get more complex.

For example the above solution would not convert the case of the received host-header, so the resulting URI has the username in exact the same case as the requester sent in host header.
It ignores the case of example.com as DNS names are not handled case-sensitive by default. But the resulting Username could be MJohnson, Mjohnson or mJOHNSON, however the host header is sent and these are normally different strings.)
So for example to always force the username in rsulting URL to be lowercase You can replace the RewriteCond line wih the following:

RewriteCond expr "tolower(%{HTTP_HOST}) =~ /^([^.]+)\.example\.com(:\d+)?$/" [NV]

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .