RunCloud Help

Sep 17, 2020

How to redirect to www or non-www

There is no official way to do this through the RunCloud panel.


Using apache htaccess to force www non-www


Most developers running their websites often want to take up the best practices for their website, especially when it comes to SSL. When it comes to adding www to a website or not, it is a sole preference placed on the developer. Google and other search engines do not favor one over the other, however, you should commit to one or the other, but you may have both as well.


If you want to use both, then you do nothing and leave everything as is. For this discussion, we will approach the best method using Apache to force a www redirect and a non-www redirect.


Using the File Manager in RunCloud, create or open a new htaccess file by typing in .htaccess. That reads dot htaccess. Nothing goes in front of the dot. Insert this code if you wish to redirect to a www domain.


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


If you wish to redirect all your www to no www, you would enter this code:


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


yourdomain.com should be your website. Everything else remains the same.


Using nginx to force www non-www


The decision to use a website the uses www as the prefix domain or a non-www prefix is solely at the discretion of the developer. With Apache, it as simple as creating a .htaccess file and entering in some code that gets read before the website is loaded. However, to do it with Nginx requires more knowledge of accessing your server via command line.


For Nginx, you cannot use File Manager or RunCloud's dashboard to redirect your website to a www version or a non-www version. You will need to use vim or nano to access the file. The file is: /etc/nginx-rc/extra.d


For redirecting non-www to www:


server {
  if ($host !~ ^www\.) {
    rewrite ^ $scheme://www.$host$request_uri permanent;
  }
}


For redirecting www to non-www:


server {
  if ($host ~* ^www\.(.*)) {
set $host_without_www $1;
    rewrite ^(.*) $scheme://$host_without_www$1 permanent;
  }
}


After you have saved the file, you will need to restart your NGINX server by typing:


sudo service nginx-rc restart


You will need to add a CNAME record with the name of www and a hostname of @ in order for everything to work properly.


Updated: 9/17/2020