简体   繁体   中英

Using fall-through rewrite for mod_vhost_alias

I run a couple dozen sites on my test VPS, and currently use mod_vhost_alias to avoid needing a new VirtualHost every time I throw up a new site. My current configuration looks like this:

<VirtualHost *:80>
  ServerName my.servername.com
  ServerAlias *
  VirtualDocumentRoot /var/www/%0/public_html
</VirtualHost>

Inside my /var/www directory, each site has its own directory. For instance, the path to my personal page is /var/www/personalsite.com/public_html/index.php. This is working great for requests to http://personalsite.com .

However, this does not work when requests come in for http:// www .personalsite.com. For some of my other sites, I have the inverse problem -- the directory may be /var/www/www.sitename.com/public_html, so requests for http://www.sitename.com are fine. However, requests for http://sitename.com do not work.

Is there a way to set up my Apache config so that when a request comes in, it does the following? Are there any performance implications of doing it this way?

In pseudocode:

1. Check if the directory or file exists. If it does, skip the rest of the rules 
       (but don't stop, in case a local .htaccess has rules in it for pretty URLs 
       in WordPress or Concrete5)
2. If the file/directory does not exist:
    1. If the host header starts with "www":
        1. remove the www from the host header and try the first rule again.
    2. If the host header does not start with "www":
        1. add "www" to the beginning  of the host header and try the first rule again
    3. If it still fails after trying both conditions:
        1. Go to a 404 error page

I'm currently doing this with about 20 virtualhosts, but that seems ridiculous when I have to add a new one for each site. The point of using mod_vhost_alias was to avoid needing all these VirtualHosts in the first place.

Assuming you're OK with redirecting users, you can use one of the techniques from https://stackoverflow.com/a/2361508/881615 :

  • either set a mod_rewrite rule to remove the leading www. from requests,
  • or set a redirect in each vhost to redirect requests with a leading www. to the top-level domain

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