I fixed it!
The trick is add conditional rewrite:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^localhost
RewriteRule ^([a-zA-Z0-9_-]+)/?$ http://%{HTTP_REFERER}/~username/mysite/profile.php?u=$1
RewriteCond %{HTTP_HOST} !^localhost
RewriteRule ^([a-zA-Z0-9_-]+)/?$ profile.php?u=$1