Httpd/Apache2 Virtual Host and Hostname Conflict

apache-2.2hostnamehttpdvirtualhost

I have a domain ie test.example.com.

I set the hostname of my server to this by uisng:

hostname test.example.com

I then add a Virtual host in /etc/httpd/conf/httpd.conf

NameVirtualHost *:80

<VirtualHost *:80>
    DocumentRoot /var/www/html/
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot /var/www/html/mydir
    ServerName test.example.com
    ServerAlias www.test.example.com
</VirtualHost>

I then restart the Httpd service. If I try to access test.example.com I get index.php in /var/www/html and not the specified folder. If I change the hostname to something other than this and then restart httpd, the virtual host works as expected, so I can only assume that when there is an incoming connection to the hostname, apache strips the url.

In php when printing

$_SERVER['REQUEST_URI']
$_SERVER['REDIRECT_URL']

I get /. Can anyone tell me how to can overcome the issue or should I keep the hostname set as something else? I have a backup script which uses the hostname as a directory name so I can organise the backups nicely, this is the main reason I have changed the hostname in the first place.

Best Answer

In your case, I would replace

NameVirtualHost *:80

<VirtualHost *:80>
    DocumentRoot /var/www/html/
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot /var/www/html/mydir
    ServerName test.example.com
    ServerAlias www.test.example.com
</VirtualHost>

by

<VirtualHost *:80>
    DocumentRoot /var/www/html/mydir
    ServerName test.example.com
    ServerAlias www.test.example.com
</VirtualHost>

# /!\ THIS HAS TO BE ON THE LAST POSITION /!\
<VirtualHost *:80 *:443>
ServerName localhost
ServerAlias *
DocumentRoot /var/www/html/
</VirtualHost>

Like that all request other than test.example.com & www.test.example.com will deliver /var/www/html/

More information : NameVirtualHost has no use in your case, and has been removed in Apache 2.4 https://httpd.apache.org/docs/2.4/en/upgrading.html

Related Topic