Server Fault is a question and answer site for system and network administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have an application that tries to connect to I would like these connections to be redirected to localhost. What is the best way to achieve this?

(I've just learned that /etc/hosts only works for DNS requests, and not for IP addresses.)

I think I need to write some iptables commands but I've never used those before.

share|improve this question

You need to add a rule like this:

iptables -t nat -A PREROUTING -p tcp --dport 80 -s source_ip -j REDIRECT --to-ports 80

The above example redirect all http requests to localhost on same port 80. Of course, you can change the ports and protocol according to your needs. However, there is one more requirement that this host should be receiving this traffic to be able to redirect it (such as your gateway).

If you don't need to filter any traffic, you can just set default policy to ACCEPT for INPUT.

share|improve this answer
I'm not only interested in port 80, I want all traffic to be redirected to localhost. – aioobe Apr 30 '12 at 12:11
@aioobe: So, you can remove the part -p tcp --dport 80 and also --to-ports 80 from the above rule. – Khaled Apr 30 '12 at 12:35
...also, I don't know what I should write for source_ip. The local IP which I want to redirect connections to or – aioobe Apr 30 '12 at 12:43
If you don't know the source IP, you can use the option -d destination_ip to apply the rule only to specific destination addresses. – Khaled Apr 30 '12 at 12:51
It could that masquerade is also needed iptables -t nat -A POSTROUTING -p all -j MASQUERADE – pl1nk Sep 11 '12 at 14:07

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.