简体   繁体   中英

Apache Differentiate domains by Virtualhost

I need to serve multiple domains from one folder with minor branding/reskinning changes. To prevent having to maintain a dozen duplicate codebases, I wanted to set an environment variable for each. I need a secure way that cannot be tampered with "in browser", so I was trying to set something prior to serving the code out.

I have the sites setup on my server and I was planning to use SetEnv SITE_CODE for each to determine which site is being served and my PHP code would use get getenv('SITE_CODE'); to determine which skin to show.

However it seems this won't work as I get the last site code for all sites. Is there something I am doing wrong or a better way to do this?

<VirtualHost *:80>
    ServerAdmin info@site1.com
    ServerName site1.com
    ServerAlias site1.com www.site1.com
    DocumentRoot /var/www/mainsite/
    ErrorLog /var/www/site1.com/logs/error.log
    CustomLog /var/www/site1.com/logs/access.log combined
</VirtualHost>

SetEnv SITE_CODE site1

and

<VirtualHost *:80>
    ServerAdmin info@site2.com
    ServerName site2.com
    ServerAlias site2.com www.site2.com
    DocumentRoot /var/www/mainsite/
    ErrorLog /var/www/site2.com/logs/error.log
    CustomLog /var/www/site2.com/logs/access.log combined
</VirtualHost>

SetEnv SITE_CODE site2

An environment variable set for Apache will affect the Apache user's environment, not a specific end user session, which is why it can't be used reliably for your purpose.

If it were me I'd do one of two things:

  1. Check the requested domain directly by examining $_SERVER['SERVER_NAME']
  2. Examine that value then set a session variable at the first request (that is, if that variable is not yet set for the current session). This would not be able to be directly tampered with, if that's important for some reason.

You can basically leave the VirtualHostConfig as it is and use SetEnvIf in your .htaccess file in your webroot folder.

SetEnvIf Host "my.site1.com" SITE_CODE=Site1

...

SetEnvIf Host "my.site2.com" SITE_CODE=Site2 and so on.

A more in-depth manual on the respective Apache directives and used modules can be found here: https://httpd.apache.org/docs/current/mod/mod_setenvif.html

And as stated in this answer: https://stackoverflow.com/a/4139899/8103283 if for example the module mod_setenvif is not available for you, mod_rewrite can also do the trick.

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