Inside virtuahost apache conf file
/etc/apache2/sites-available/000-default.conf
I tried to put these code inside apache conf file
ServerName example.com
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule ^/(.*)$ http://www.example.com/$1 [L,R=301]
also I tried,
< If "%{HTTP_HOST} != 'YOUR-DOMAIN.com'">
Redirect "/" "http://www.YOUR-DOMAIN.com/"
</If>
also did this
<VirtualHost *:80>
ServerName example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost *:80>
ServerName www.example.com
# real server configuration
</VirtualHost>