What’s the recommended way to set the site URL?

31

22

There are multiple ways to set the site URL. What is the recommended way?

Brandon Kelly

Posted 2014-07-10T21:12:15.417

Reputation: 27 245

Answers

45

As of Craft 2, you should be using the new siteUrl config setting.

There are two advantages to setting your site URL using this config setting.

First, The value can be set on a per-locale basis, in a way where Craft is actually aware of all locales’ URLs on every request (unlike the CRAFT_SITE_URL constant, where Craft only knows the current locale’s URL). That’s a good thing because it means you can easily link to entries’ URLs across different locales, for example.

return array(

    'siteUrl' => array(
        'en_us' => 'http://example.com/',
        'de'    => 'http://example.com/de/',
    ),

    // ...

);

Its value can also be set directly on a per-environment basis. (Yes you can achieve this using the environmentVariables config setting combined with a {siteUrl} tag inside the Site URL setting within the CP’s general settings, but that’s much less direct/obvious.)

return array(

    '.dev' => array(
        'siteUrl' => 'http://example.dev/',
        // ...
    ),

    '.com' => array(
        'siteUrl' => 'http://example.com/',
        // ...
    ),

    // ...
);

Those of course can be combined as well:

return array(

    '.dev' => array(
        'siteUrl' => array(
            'en_us' => 'http://example.dev/',
            'de'    => 'http://example.dev/de/',
        ),
        // ...
    ),

    '.com' => array(
        'siteUrl' => array(
            'en_us' => 'http://example.com/',
            'de'    => 'http://example.com/de/',
        ),
        // ...
    ),

    // ...

);

Brandon Kelly

Posted 2014-07-10T21:12:15.417

Reputation: 27 245

3

I just switched over to setting siteUrl this way, but it seems like the variable doesn't get parsed anymore in the asset sources? Here is what my config looks like: https://gist.github.com/davist11/aea165a093b20e159782

– Trevor Davis – 2014-07-14T18:53:35.537

8

If you want to use a {siteUrl} tag in your asset source settings, you will still need to define a 'siteUrl' key in your environmentVariables array. That may change in the future though, since it would be handy.

– Brandon Kelly – 2014-07-14T19:00:51.060

Got it, thanks! – Trevor Davis – 2014-07-14T19:01:26.463

2

It's worth noting that for security reasons you should not set siteUrl dynamically with HTTP_HOST https://ellislab.com/blog/entry/http-host-and-server-name-security-issues

– mjr – 2016-07-01T14:34:42.763

What value should be entered in the CP General Settings Site URL field when using the siteUrl config setting? – Marion Newlevant – 2014-11-26T19:53:06.370

1@MarionNewlevant if the siteUrl config setting is set, the CP setting is irrelevant. – Brandon Kelly – 2014-11-27T04:17:31.777