Search code examples
database.htaccesscodeigniterconfigno-www

CodeIgniter: server name without www does not pick the correct DB config


If I go to url of http://www.example.com I get a nice redirect to http://www.example.com/site/index.php/home/main just as I want using the .htaccess file.

If I cut the WWW part, meaning http://example.com then I get the following error:

An Error Was Encountered
No database connection settings were found in the database config file.

My htaccess file:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /example/index.php?/$1 [L]  

RedirectMatch 301 ^/$ /home/main/

while in database.php I have

 if (
    ($_SERVER['SERVER_NAME'] == 'www.example.com') 
    or ($_SERVER['SERVER_NAME'] == 'example.com') 
    or ($_SERVER['SERVER_NAME'] == 'example.anothersite.com')
    or ($_SERVER['SERVER_NAME'] == "NN.NN.NN.NN")
)
{
    $db['default']['hostname'] = 'localhost';
    $db['default']['username'] = .....

What am I missing? I need it to work with or without WWW and it seems to be an issue in my CodeIgniter since the error is a CodeIgniter one.

Thank you!


Solution

  • It is amazing how brain works after a break. To fix this I needed a break, honestly.

    My link was pointing to a VirtualServer, problem was that the www.example.com was pointing to the correct server while I had no VirtualServer file for "example.com" and it was simply taking the first file (wrong one obviously) and it was in the wrong CodeIgniter folder and wrong database file.

    So to fix I simply need to edit the apache directive and add, after "ServerName www.example.com" section another section for no www, which looks like this:

    ServerName example.com
    ServerAlias example.com
    DocumentRoot "/home/example/public_html"
    <Directory "/home/example/public_html">
        AllowOverride All
        allow from all
        Options Indexes FollowSymLinks MultiViews Includes ExecCGI
        Require all granted
    </Directory>
    

    And this fixed my issue