Approach proposed by Sunny and CesarB:
iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
works fine but it has a small drawback -- it does not prevent user from connecting directly to port 8080 instead of 80.
Consider the following scenario when this can be a problem.
Let's say we have a server which accepts HTTP connections on port 8080 and HTTPS connections on port 8181.
We use iptables to establish the following redirections:
80 ---> 8080
443 ---> 8181
Now, let's suppose our server decides to redirect user from a HTTP page to a HTTPS page. Unless we carefully rewrite the response, it would redirect to https://host:8181/. At this point, we are screwed:
- Some users would bookmark the
https://host:8181/ URL and we would need to maintain this URL to avoid breaking their bookmarks.
- Other users would not be able to connect because their proxy servers do not support non-standard SSL ports.
I use the following approach:
iptables -t mangle -A PREROUTING -p tcp --dport 80 -j MARK --set-mark 1
iptables -t mangle -A PREROUTING -p tcp --dport 443 -j MARK --set-mark 1
iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 8181
iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport 8080 -m mark --mark 1 -j ACCEPT
iptables -I INPUT -m state --state NEW -m tcp -p tcp --dport 8181 -m mark --mark 1 -j ACCEPT
Combined with default REJECT rule on the INPUT chain this approach prevents users from connecting directly to ports 8080, 8181
socket.error: [Errno 13] Permission denied– Kazark Nov 15 '11 at 15:15