问题描述:

I use a custom framework which has many sub applications. I want to assign a domain to each application folder but ran into an issue.

Apache vhosts config

<VirtualHost *:80>

ServerName app1.com

DocumentRoot /var/www/framework/public/app1

</VirtualHost>

<VirtualHost *:80>

ServerName app2.com

DocumentRoot /var/www/framework/public/app2

</VirtualHost>

/var/www/framework/.htaccess

DirectorySlash Off

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*?)/?$ index.php?_ROUTE=$1 [QSA]

/var/www/framework/index.php

<?php

exit('WORKED!');

//Route request

//...

Everything's works fine except that it tries to use the index.php file in the document root such as "/var/www/framework/public/app1/index.php" when actually I want to use the index file "/var/www/framework/index.php".

So how would I get it to use the index.php file two directories above or relative to the .htaccess location?

网友答案:

You don't. The .htaccess will only be read starting at the root folder of the virtualhost.

You either need to clone the file (ugly unless you're using something like a source code repository to pull it as an external) or add it to your vhosts config. I'd recommend just making one 'rewrite.conf' file and loading it through the vhosts config through include.

vhosts conf:

<VirtualHost *:80>
    ServerName app1.com
    DocumentRoot /var/www/framework/public/app1
    Include rewrite.conf
</VirtualHost>
<VirtualHost *:80>
    ServerName app2.com
    DocumentRoot /var/www/framework/public/app2
    Include rewrite.conf
</VirtualHost>

rewrite.conf:

DirectorySlash Off
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*?)/?$ index.php?_ROUTE=$1 [QSA]

This does have a few drawbacks:

  • You'll need to reset the server every time you change it.
  • If you have a lot of rewrites, you'd probably want to keep this somewhere at the code level... however, I'd argue that you probably want a different solution (as in, a PHP handler) if you have a whole mess of rewrites.

Note that you could also just do the same rewrite directly in the .htaccess, but if you're going to do it, lower level seems better.

网友答案:

What you're doing is essentially a multi-site application.

You should set the document root to the folder that contains the main index.php file. Then that should route the request to the required app by checking the HTTP host property in the $_SERVER superglobal, like for example:

switch ($_SERVER['HTTP_HOST']) {
    case 'app1.com':
        include 'app1/index.php';
        // Do stuff
        break;

    case 'app2.com':
        include 'app2/index.php';
        // Do stuff
        break;
}
相关阅读:
Top