34

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

1 Answer 1

48

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/',
        ),
        // ...
    ),

    // ...

);
5
  • 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: gist.github.com/davist11/aea165a093b20e159782 Commented Jul 14, 2014 at 18:53
  • 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. Commented Jul 14, 2014 at 19:00
  • What value should be entered in the CP General Settings Site URL field when using the siteUrl config setting? Commented Nov 26, 2014 at 19:53
  • 1
    @MarionNewlevant if the siteUrl config setting is set, the CP setting is irrelevant. Commented Nov 27, 2014 at 4:17
  • 2
    It's worth noting that for security reasons you should not set siteUrl dynamically with HTTP_HOST ellislab.com/blog/entry/…
    – mjr
    Commented Jul 1, 2016 at 14:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.