Could we use ruby and use the URI parsing to do this? It should be a uri and the things you need to extract/replace are hostname and port, which might be doable with URI.