220

Can I map an IP address like 127.0.0.1 to a domain name and a port?

For example, I would like to map 127.0.0.1 to api.example.com:8000

vvvvv
  • 25,404
  • 19
  • 49
  • 81
Carson
  • 17,073
  • 19
  • 66
  • 87
  • 6
    You cannot map the port number in /etc/hosts. Instead you can define as `127.0.0.1 api.mydomain.com` and access it in the browser like `api.mydomain.com:8080` – Fizer Khan Oct 15 '13 at 06:54
  • I read somewhere that dns supports this. You can have a record that says on www.example.com http is on port 80 and also an A record to say that the address is 127.0.0.1 it also said it was not well supported. It did not say much after that. – ctrl-alt-delor Feb 05 '14 at 11:28

2 Answers2

224

No, that's not possible. The port is not part of the hostname, so it has no meaning in the hosts-file.

mata
  • 67,110
  • 10
  • 163
  • 162
166

If you really need to do this, use a reverse proxy. For example, with Nginx:

server {
  listen       api.mydomain.com:80;
  server_name  api.mydomain.com;
  location / {
    proxy_pass http://127.0.0.1:8000;
  }
}
Eric Fortis
  • 16,372
  • 6
  • 41
  • 62
  • 5
    I think the line of proxy_pass should look like this: `proxy_pass http://127.0.0.1:8000;` I got "invalid URL prefix" on nginx 1.4.3. – Nobu Oct 23 '13 at 21:41
  • thanks for this wonderful tip! simple solution for most servers. – micahscopes Dec 29 '16 at 21:26
  • I am using this trick to map ports of a remote machine (e.g. http://cloud.app:80 while the actual port is 8080). Very useful for testing Confluence nodes of a cluster but accessing them on the same base URL. Thanks! – Gábor Nagy Mar 07 '17 at 11:46
  • 13
    I had basically the same problem and the solution using this reverse-proxy is really helpful. Although, I wanted some simpler solution so I made this tool: https://github.com/cristianoliveira/ergo I hope it help in somehow :) – Cristian Oliveira Aug 20 '17 at 18:02
  • Thanks @CristianOliveira ! This helped me a LOT :) – Bruno Duyé Nov 29 '18 at 23:46