SilverStripe. How to redirect from www.domainName to domainName?

醉酒当歌 提交于 2019-12-13 17:11:02

问题


I'm looking to find the reverse of the method:

Director::forceWWW();

My main domain should be domainName.com without www.


回答1:


3dgoo's solution is faster since it does not involve any php but I did...

class PreventWWW extends DataExtension {
    public static function stopWWW() {
        if(!(strpos($_SERVER['HTTP_HOST'], 'www') !== 0)) {
            $destURL = str_replace(Director::protocol() .'www.', Director::protocol() , 
                Director::absoluteURL($_SERVER['REQUEST_URI']));
            header("Location: $destURL", true, 301);
            die("<h1>Your browser is not accepting header redirects</h1>"
                . "<p>Please <a href=\"$destURL\">click here</a>");
        }
    }
}

in yml config:

Director:
  extensions:
    - PreventWWW

since I set it just on live-env I had this in _config.php

PreventWWW::stopWWW();

It should also be possible to set it dependent on environment (live/dev/stage) in yml per "Only". See here.. http://doc.silverstripe.org/framework/en/topics/configuration




回答2:


There is no SilverStripe function to redirect all www links to non www links.

Instead, you can write a .htaccess RewriteRule to do this.

In your website root .htaccess file add the following code under the existing RewriteEngine On line:

...

<IfModule mod_rewrite.c>
    SetEnv HTTP_MOD_REWRITE On
    RewriteEngine On

    ### Redirect www links to non www links ###

    RewriteCond %{HTTP_HOST} ^www\.domainName\.com$ [NC]
    RewriteRule (.*) http://domainName.com/$1 [R=301,L]

    ...


来源:https://stackoverflow.com/questions/26021385/silverstripe-how-to-redirect-from-www-domainname-to-domainname

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!