You can use ConnectAPI for detecting community
public class CommunityHelper{
public static String communityId=Network.getNetworkId();
public static ConnectApi.Community getCommunityInfo(){
if(communityId!=null){
return connectapi.Communities.getCommunity(communityId);
}else {
return null;
}
}
}
If community Id is null then you are not in community and for User In community you will see community object being returned .
Edit
The only way I see is to use Id.getsobjecttype() to get object name and use custom setting to store object name and then store the different URL there and Use redirection to specified URL in custom setting