Contents
- 1 Introduction
- 2. Connecting the Past and the Future: My Redefinition of the Gateway
- 3 Why don’t I just use Apple TV as a “bypass gateway”?
- 4. Build a lightweight and stable "bypass gateway"
- 5 Deploy redsocks2
- 6 Enable kernel IP forwarding
- 7 iptables configuration
- 8 Conclusion
1 Introduction
Speaking of the scientific environment in my home, after three major optimizations, the structure is as follows:

Currently, this structure works well. If a device in the intranet needs to have "global" scientific capabilities, you only need to associate the source IP address of the device with the wan2 port of iKuai (connected to the LAN port of AC86u) in "Flow Control and Diversion" - "Diversion Settings" - "Port Diversion" on iKuai:

In order to deal with special situations when AC86u fails, an openwrt virtual machine with opencalsh installed is deployed in the intranet PVE as an emergency device:

For detailed construction process, see the article:Discussion on the best deployment scheme of soft router series iQuick+openwrt (goodbye, bypass router).
However, existing solutions also have some limitations:
- Depends on specific hardware routers
The current solution relies on routers such as iQuick and AC86u (or openwrt) that have scientific Internet access capabilities. However, few families have iQuick or routers with scientific capabilities. Therefore, for users who do not have these devices, this solution is actually meaningless. Even for me, if China Telecom cancels its support for 3-way dialing one day, I will definitely not use iQuick anymore. And if the AC86u router breaks down, I may not be willing to spend a high price to buy a better one. In either case, this solution will fail.
- Many devices actually only need "local" scientific Internet access
In fact, for most intranet devices, "local" scientific Internet access is enough. For example, my productivity device (Mac mini) and NAS as a PT downloader do not need global scientific Internet access, especially for devices that need to frequently access domestic content, global science may bring side effects (slow access or airport package traffic is wasted). Therefore, for these devices, scientific Internet access is only needed in specific scenarios, such as accessing certain blocked websites through the Chrome browser, or certain local applications that require science to work properly (such as GitHub Desktop), and these needs can be met through browser smart proxy plug-ins (such as SmartProxy) or network proxy tools (such as Proxifier), combined with the HTTP proxy function provided by Shadowsocks on Apple TV, without the need for global science.
Based on the above considerations, and considering that the existing Apple TV already provides HTTP proxy services through Shadowsocks (of course, it can also be replaced by proxies provided by other scientific software on Apple TV, or HTTP or SOCKS5 proxies on other devices, and Apple TV is not required), I hope to build a lightweight, stable, and low-latency bypass gateway solution that does not rely on export routers and can be independently deployed on the intranet on this basis, thereby building a system that can cover the scientific Internet access needs of all devices on the intranet: for devices that require "local" scientific capabilities, directly use HTTP proxy access; and for a small number of devices that require "global" scientific capabilities, access is forwarded through the bypass gateway.
After determining the need to build a bypass gateway, a common idea is to use scientific Internet access software based on transparent proxy (TProxy) or virtual network card (TUN) to achieve automatic forwarding of intranet traffic. This type of solution is technically mature and has extensive community practice support.
However, considering that I already have a stable and available HTTP proxy service (the stability of Apple TV is still very reassuring), if I redeploy a complete proxy system based on TProxy or TUN, it will not only increase the complexity of configuration and maintenance, but may not necessarily bring substantial advantages. Therefore, I turned to thinking about whether I can build a more concise, efficient, lightweight and stable bypass gateway around the existing HTTP (or SOCKS5) proxy.
2. Connecting the Past and the Future: My Redefinition of the Gateway
This article will discuss "Bypass Gateway" in the future. The word "gateway" often has different meanings in different technical contexts. In order to avoid misunderstandings and facilitate the analysis in the following text, I intend to split, sort out and define the meaning of "gateway" in a more practical context. It can be said that this is a"Redefinition" with my personal understanding and practical backgroundI hope this will help you better understand the core issues faced when building a bypass gateway solution.
In network projects, "gateway" is an often mentioned but easily misunderstood role. In simple terms, the responsibilities of a gateway areReceives data frames sent by devices in the same broadcast domain whose target MAC address is its own (L2 layer), strips out the data packets (L3 layer, even if the target IP address of these data packets is not its own), and then completes the processing or forwarding action according to the established strategy.
In the scope of this article, a qualified gateway needs to have the following capabilities:
- L3 layer packet recognition and reception capabilities
It must be able to identify and receive data packets whose destination IP is not its own. Because for most conventional devices, if the destination IP is inconsistent with its own network card IP, it will not receive the data packet unless the network card is in promiscuous mode or a specific forwarding mechanism is enabled. The reason why the gateway device is an "exception" is that it is designed to do things for others.
- Packet processing decision-making capabilities
The gateway device needs to make decisions on the received data packets based on pre-set policies: How should it handle this packet?
Such strategies may include: querying the routing table to determine the next hop, making ACL judgments based on the rule engine, and applying traffic diversion tools to determine whether they are scientific.
Once a judgment is made, the device will send the data packet to the corresponding subsequent processing module, such as direct routing forwarding, NAT mapping, or other more complex intermediate processing logic.
- Protocol conversion capability (one of the intermediate processing logic)
During the processing, some data packets are not suitable for direct forwarding according to the original protocol, but need to enter a specific "protocol conversion path" to complete cross-protocol and cross-system bridging. This is very common in many practical scenarios:
- for example VoIP Gateway, which is responsible for converting analog signals in traditional telephone networks (such as PSTN) into IP-based voice protocols (such as SIP or H.323), thereby achieving intercommunication between traditional telephones and Internet voice calls;
- Another example NAT64 Gateway, used in an IPv6-only network environment, to automatically convert IPv6 requests into IPv4 packets to support access to traditional websites that do not have IPv6 support.
These "protocol conversion gateways" enable "translation-based conversations" between systems that were originally unable to communicate by assuming the responsibility of intermediate bridging. Such conversion logic will also become an indispensable part of certain types of bypass gateways.
Although the gateway in most home networks may not involve complex protocol conversion,This ability becomes particularly critical once you have to cross the "language barrier" between network protocols.——This is also the part that this article will focus on later.
- Final forwarding of the packet
After completing policy decisions and protocol processing, the gateway needs to send the data packet to the "next station".
The meaning of this next stop depends on the previous processing path:
- If it is traditional routing forwarding, it may be a certain LAN/WAN port, accompanied by NAT or routing jump;
- If it is scientific traffic based on policy diversion, it may be a transit server at the airport;
- If protocol conversion is performed, the "next stop" may be a local or remote HTTP/SOCKS proxy server.
In short, the task of the gateway is to complete the complete link of "receiving → decision → optional conversion → forwarding".Only when it possesses these four capabilities can it be called a "real" gateway.
But it should be noted that:
1. Identification and processing are only part of the job, performance is the key to competence
In some professional scenarios, such as the three-layer switch in the enterprise network, the identification and forwarding of data packets are usually completed by dedicated ASIC chips, which can achieve line-speed processing and high efficiency. In home or self-built environments, most gateway devices (including bypass methods) rely on the CPU of their own system to handle all of this: whether through iptables, nftables, ebtables, or redsocks2, Clash, tun2socks and other tools, the processing logic of these flows requires CPU intervention.
Although this approach brings a high degree of flexibility, it also places higher demands on system resources:Once the device performance is insufficient, the strategy is complex, or the concurrency is too high, the forwarding capability may become a bottleneck, resulting in high latency, packet loss, or even the risk of the entire network being paralyzed.
2. A gateway may not be just one device, but may also be a system composed of multiple devices.
When many people think of "gateway", they think of a device: it may be a soft router or a bypass gateway. But in fact,The role of a gateway is to be a "path connector" and a "protocol converter", not to "cram all functions into one device".In actual deployment, especially in scenarios that require flexibility, modularity, or high availability, the functions of a gateway can be completely decomposed into multiple roles and completed by multiple devices in collaboration.
3 Why don’t I just use Apple TV as a “bypass gateway”?
In the previous section, I explained the concept of "gateway" because it involves the reason why I do not use Apple TV directly as the so-called "bypass gateway" of the intranet in this article, although many tutorials on the Internet take it for granted that Apple TV is used directly as a "bypass gateway":

In fact, strictly speaking,Apple TV does not have the necessary features to be a true “gateway”: It is essentially a consumer-grade media terminal. It is not a device designed for network forwarding, nor does it have any ability to receive and process data packets whose destination IP is not its own. In other words, if you point the default gateway of a device in the LAN to Apple TV, if the data packet it receives is not sent to its own IP, it isI won't careIn this regard, Apple TV does not meet the core capability we mentioned earlier, that is, "the gateway must be able to forward packets whose target IP is not its own IP."
But in reality, some people will find that under certain conditions, Apple TV seems to "magically" have some traffic forwarding capabilities, and can even be used as a "proxy gateway". This is actually because another less noticed factor is involved:HomeKit Home Hub Features:


This feature was originally designed to allow Apple TV to act as a control center in the HomeKit network to coordinate some smart devices (such as Thread or low-power Bluetooth devices) that do not have complete network configuration capabilities to access the Internet: when the home hub function is turned on, Apple TV will temporarily turn on a service similar to "shared Internet access", receiving traffic whose target IP is not its own, and then converting the source address of the received traffic into its own IP according to the local routing and forwarding it out (actually single LAN port forwarding + NAT). If scientific software happens to be installed on Apple TV at the same time, then when a device in the local area network points the default gateway to its interface IP, Apple TV can indeed provide scientific capabilities.
However, although this ability is technicallyIt does "look like a gateway", but in essence it is still a mechanism that is temporarily "released" for specific purposes. It is hard to say how stable it is, and it cannot assume the high-performance, high-throughput role of a true gateway (Apple itself has not mentioned in any document that Apple TV can also be used as a gateway after turning on the home hub function. It can't be a hidden benefit~). Some netizens have actually realized this problem:

And the Surge team has also issued a warning against this usage:

In short, after turning on the home hub function, Apple TV can indeed take on some of the work of a "bypass gateway", but this is just a "side job" by coincidence and is not the role it should play. Therefore, "usable" does not mean "suitable" or "reliable".
Essentially, Apple TV has many restrictions on the permissions of various apps installed on it (including scientific Internet software). The positioning of these scientific software is toBarely meets the scientific Internet needs of Apple TV itself, rather than to build a complete scientific gateway. Given that most of the traffic on Apple TV is HTTP/HTTPS communication based on TCP protocol, these software can provide a basic HTTP proxy function to the outside world, which is quite good.
In short: Apple TV as a bypass gateway is not a serious solution.Single device temporary emergencyIt can be used occasionally; but if you want to cover multiple devices or even use it stably for a long time, forget it - whether it is performance, controllability, or stability, the gap between it and the real gateway is very obvious.
4. Build a lightweight and stable "bypass gateway"
4.1 Overview
In a home network, although the bypass gateway does not directly assume the responsibility of network egress, it plays a key role as a "transfer station" - it intercepts or receives traffic from internal network devices and determines where the traffic should be sent based on specific policies. In this process, the cooperation of two types of core tools really plays a role:Network traffic forwarding tool(such as iptables, nftables) andProxy Protocol Forwarder(such as redsocks2, tun2socks).
The former is responsible for "bringing in traffic" and deciding which traffic needs to be intercepted and redirected; while the latter is responsible for "how to handle this traffic" - it can be to convert the original network request into HTTP or SOCKS and other proxy protocol formats and then hand it over to the upstream proxy, or directly hand the traffic over to scientific programs on the local machine (such as Clash, Shadowsocks) for further processing. Understanding the division of responsibilities and collaboration between these two types of tools is the core of designing an efficient, stable, and easy-to-maintain bypass gateway solution.
This section will analyze the functional features, common options and adaptation scenarios of these two types of tools one by one, and finally select the combination that best suits the usage scenario of this article.
In my previous articles, I have clearly expressed my reservations about the "single-arm bypass routing" mode implemented by traditional OpenWRT, especially the practice of pointing the default gateway of the intranet device directly to the WAN port of OpenWRT. Although the deployment is simple, there are many problems: once OpenWRT fails, the entire network will be disconnected; OpenWRT will consume unnecessary performance to process a large amount of direct connection traffic that does not need to be "scientific"; NAT coordination and port mapping between the main router are also prone to problems.
Similarly, using Apple TV as a so-called "bypass" gateway essentially adopts a similar idea: all traffic from intranet devices is processed by the proxy tool installed on Apple TV (the most important thing is to rely on the additional capabilities provided by the "home hub" function). This method looks fresh, but in fact it is just replacing OpenWRT with Apple TV. The technical shortcomings, single point of failure, poor controllability and other problems still exist.
Therefore, I would like to emphasize one point:The concept of "bypass gateway" discussed in this article is completely different from the "bypass router" tutorials widely circulated on the Internet.: Although the names and deployment methods are similar, the structures, ideas, and goals are completely different.
What I mean by a "bypass gateway" is aA transfer role designed specifically for "proxy forwarding" scenarios:It is not responsible for providing NAT or acting as a network egress, but focuses on receiving all external access traffic (imported through the default gateway or policy routing)Receive and convert the request packets of proxy protocols (such as HTTP, SOCKS) uniformly, and then forward them to the upstream proxy server.
This may sound like a traditional "bypass router" - after all, it is also receiving all the traffic that needs to go online. But the real difference isIts responsibilities are clear and specific, and it does not participate in unnecessary complex network functions such as NAT, flow control, DNS hijacking, etc., so it is lighter and more stable in structure, and its performance overhead is more centralized and controllable..
In other words, it is not a multi-function router that "want to manage everything", but aOnly responsible for forwarding proxy trafficYou can think of it as a simplified node.Protocol Translator——When traffic comes in, it only does one thing: translate it into the proxy protocol, and then immediately transfer it to the remote proxy server for processing. There is no caching, no analysis, and no decision-making. The whole process is clean and neat, without any delay.
Because of its single responsibility and simple implementation, it has very low performance requirements for running equipment. Under this "simple and complex" architecture, it can still bring considerable scientific Internet access performance, suitable for deployment and use by users who pursue stable and efficient forwarding.
Such a node can be deployed in an LXC container or a lightweight virtual machine and decoupled from the main router. The main router still assumes the core control and traffic scheduling responsibilities of the entire network, while the bypass gateway node only serves a small number of devices that require global scientific capabilities. This decoupling design not only improves the flexibility and controllability of the proxy link, but also avoids node anomalies in most cases.The core functions of the entire network are damagedThe risk of - of course,For terminal devices that configure the bypass gateway node as the default gateway, access anomalies may still occur due to the loss of connection, but such impact is usually locally controllable and will not affect the entire system..
Therefore, this article is not to overturn the "single-arm bypass routing", but to build a clearer architecture concept and tool combination.A more modern bypass gateway solution that better meets actual needs.
4.2 Introduction to network traffic forwarding tools
4.2.1 Overview
In the previous content, we discussed the various capabilities of the "gateway" as a network traffic transfer station: it receives the data flow whose target IP is not its own, makes a judgment according to the pre-agreed decision, transfers it to the subsequent functional module (such as the protocol processor) for processing, and then forwards it in some way.The core of the entire process from receiving data packets to the protocol converter is the system's traffic forwarding tool.(Corresponding to points 1 and 2 of gateway capabilities).
For Linux-based systems, network traffic forwarding, redirection, and release are usually handled by the netfilter framework in the kernel. There are two main interfaces for users to interact with netfilter through commands or scripts:iptables and nftables.
The two tools have similar goals, both of which are used to formulate complex traffic processing rules, but the styles, syntax, and applicable eras are slightly different. When actually deploying a bypass gateway, we only need to configure a small number of rules to intercept and redirect the target device's traffic, so there is no need to delve into all of its mechanisms. However, it is still necessary to understand the differences between them and the reasons for choosing one tool over the other.
In this chapter, we will briefly introduce their respective backgrounds, characteristics, and usage recommendations to help you make appropriate choices when deploying your own gateway forwarding rules.
4.2.2 iptables: An old but still widely used traffic control tool
Iptables can be said to be the first stop for most people to get in touch with Linux network control. It has been widely used since the Linux 2.4 kernel, and manages the life cycle of network traffic through four "tables" (filter, nat, mangle, raw) and five "chains" (INPUT, OUTPUT, FORWARD, PREROUTING, POSTROUTING).
Although its syntax is imperative and not very user-friendly, it has a lot of information and a mature community.Especially in distributions such as Debian and Ubuntu, iptables is still used by default even today., so in many actual deployment scenarios, continuing to use it is the simplest and most direct solution.
If you are using an older version of LXC, a Docker-based image, or just want to get the job done with minimal fuss, iptables can handle your traffic redirection and forwarding needs.
4.2.3 nftables: A new generation framework for the future
As the kernel evolved, iptables became more and more complex in terms of modularity and rule extension, which eventually led to nftables, its more modern successor, which was introduced in Linux 3.13 and aims to unify and simplify firewall management.
Compared to iptables, nftables provides more consistent syntax, structured data support, and built-in debugging tools. More importantly:It is the main direction of the future netfilter system.
Many new distributions (such as newer Debian, Fedora, Arch Linux) have nftables enabled by default, and iptables indirectly calls nftables through the iptables-nft compatibility layer at the bottom layer. That is to say, although you are writing iptables on the surface, the actual kernel follows the rules of nftables.
However, precisely because of the existence of this compatibility layer, using both at the same time on some systems may cause confusion in the rules.If you plan to maintain this set of forwarding rules for a long time and the system has good default support, it is recommended to use nftables directly.
4.2.4 My suggestion
For a scenario like bypass gateway with clear functions and simple rules, the difference between the two is not obvious. When making a choice, you may wish to follow this principle:
- Use the one provided by the system by default.
- If you are not familiar with the syntax, the one with more online tutorials is usually iptables, which is suitable for quick implementation.
- If you want to flexibly expand more control rules in the future, or if you are using a newer system environment (such as Debian 12, Ubuntu 22.04 and above), you can directly choose nftables.
4.3 Introduction to Proxy Protocol Forwarder
4.3.1 Overview
In the previous chapters, we have intercepted the received data packets through traffic forwarding tools (such as iptables/nftables) and redirected them to a local or remote port, but this is only the first step. Next, there must be a component toReceives these raw TCP/IP traffic and converts them into proxy protocols (such as HTTP, SOCKS5) that the upstream proxy server can understand, this component is calledProxy Protocol Forwarder(Corresponding to point 3 of gateway capabilities).
4.3.2 redsocks2
redsocks It is one of the earliest traffic forwarding tools. Its design goal is to be simple and direct: listen to a local port, receive TCP traffic, repackage it into proxy protocol traffic (support HTTP CONNECT, SOCKS4/5), and then send it to the specified upstream proxy server.
What we are more concerned about here is the magic modification based on redsocks redsocks2(It is still called redsocks, but it is usually called redsocks2 to distinguish it from others.) It has made many enhancements to the original version, such as:

Note 1: It should be noted thatredsocks2 It is maintained by the community on its own initiative.Not an official release, but it has become the de facto standard in many actual projects (especially bypass gateway projects). Its official github address is "https://github.com/semigodking/redsocks".
Note 2: If you are using a proxy service that still supports the Shadowsocks protocol, redsocks2 can also connect directly as a client without the need to build an additional local proxy program. This is a built-in feature. However, it should be noted that Shadowsocks, as an early designed protocol, is now gradually regarded as an "old protocol" in actual use: on the one hand, its protocol features are more obvious,Easy to identify and interfere withOn the other hand, in terms of connection stability and anti-interference, it is gradually difficult to meet the needs of more complex network environments. Therefore, most of the current high-availability proxy solutions have turned to more modern protocol stacks, such as VLESS, trojan, Reality, etc. Therefore, this article still focuses on the role of redsocks2 as a protocol forwarder, mainly used in conjunction with existing HTTP or SOCKS5 proxies, rather than using it as a "shadowsocks" client.
4.3.3 2. tun2socks
tun2socks It is another traffic forwarding idea. Its core difference is that it does not process TCP/UDP traffic separately, but simulates a virtual TUN device, redirects all traffic to this virtual network card, and then directly does SOCKS5 proxy forwarding before the kernel protocol stack.
Features of tun2socks:
- Mainly based on SOCKS5 protocol (some versions support HTTP CONNECT)
- Can transparently proxy the entire device (such as Android, OpenWRT)
- Better support for UDP (depending on the implementation version)
- Moderate performance but simple architecture
generally,tun2socks is suitable for transparent proxy of the whole machineFor example, on mobile phones, routers and other devices, the proxy is directly exported through the TUN device. If you just want to intercept traffic on a specific port/rule, tun2socks is a bit like "using a cannon to kill a mosquito".
4.3.4 My suggestion: redsocks2
In fact, my goal for building the bypass gateway this time is very clear: I hope it can be lighter and more stable, and the key is to make it easy to deploy and maintain. redsocks2 just meets these requirements. Its performance has always been very reliable, and it is not easy to have problems when running, which is particularly suitable for being placed on this kind of "plug and play" relay node. Moreover, the configuration is very intuitive, and there is no need to mess up the TUN virtual network card or modify the routing table, which saves a lot of trouble. What's more, it supports multiple upstream proxy protocols, especially HTTP, which can be used with the HTTP service provided by Shadowsocks running on my Apple TV.
Overall, redsocks2 is the most suitable solution for the current bypass gateway scenario: it is light, stable, and worry-free.
4.4 Final forwarding destination
In the "bypass gateway" scenario discussed in this article, the task of the proxy protocol forwarder (redsocks2 is used in this article) is to redirect the traffic intercepted by iptables or nftables.Perform protocol conversion based on the actual configured upstream proxy typeThen forward it to the upstream proxy server (gateway capability point 4).
As for the type of upstream proxy server, there is no mandatory requirement. You can choose HTTP proxy or SOCKS5 proxy according to your network environment. Take my own situation as an example: because I have an Apple TV at home and installed Shadowrocket, it happens to provide a usable HTTP proxy, so I directly use this ready-made exit. If you have a stable SOCKS5 node yourself, that is completely fine.For redsocks2, the configuration only requires specifying the correct proxy protocol and address. There is no essential difference between the two.
It should be noted that:iptables/nftables, redsocks2, and the final proxy service itself do not need to be deployed on the same device(Of course, it is no problem to deploy them on the same device). You can design the most appropriate structure according to your actual situation, such as:
- My own deployment method is to deploy iptables/nftables and redsocks2 together in an LXC container
- Shadowrocket, which runs separately on Apple TV, provides HTTP proxy as the final exit.
This architecture has clear decoupling and is easy to maintain. If any link fails, it is also easier to locate and replace.There is no fixed answer to how to implement a bypass gateway. The key is to make the most secure and worry-free deployment based on your own network environment and equipment capabilities.
5 Deploy redsocks2
5.1 Environment Description
Since the HTTP proxy is ready-made (provided by Shadowrocket on Apple TV), I mainly need to deal with redsocks2. For the best performance, use LXC to deploy redsocks2.
Although I have quite a few LXCs running on my PVE, they all have their own uses:

After thinking about it, I decided to create a new Debian LXC to deploy redsocks2. I can use iptables on this LXC to intercept traffic and redirect it to the local redsocks2. It is simple and convenient:

Note 1: I have already written about the specific steps of creating LXC in my previous article, so I will not repeat it here. If you are not clear about it, you can refer to the article.Docker series uses LXC to set up a Minecraft Bedrock Edition server based on Turnkey-gameserver".
Note 2: redsocks2 LXC does not require too many resources. For example, 1-2 CPU cores are enough, and 256MB or 512MB of memory is enough. The actual situation depends on the actual usage of the bypass gateway in your home.
Note 3: I used LXC because I already had PVE.Ubuntu / DebianYou can use bare metal or LXD directly.Alpine Linux / Arch / GentooIt also natively supports LXC, and QNAP's NAS can also be run using Linux Station. In short, just choose the method that suits you.
Note 4: The same is true for virtual machines, except that compared to LXC, virtual machines consume a lot more resources. I think it is not cost-effective. For virtual platforms that do not support LXC, you can just use virtual machines directly.
Note 5: For the initialization of the Debian system, please refer to the article"Summary of general initialization steps for Debian series systems".
5.2 Install redsocks2
1,Install Dependencies
apt update apt install -y build-essential libevent-dev libssl-dev git pkg-config
Explain the role of each package:
- build-essential: Contains basic building tools such as gcc and make.
- libevent-dev: The main event-driven library dependency of redsocks.
- libssl-dev: OpenSSL development package, providing encryption support.
- git: This is needed if you haven't cloned the repository yet.
- pkg-config: Some makefiles will use it to check dependency versions and compilation parameters.
In order to avoid tedious troubleshooting due to missing functions or compilation failures, I chose to enable all modules of redsocks2 at once (mainly to avoid compilation errors).
2,Clone the source code and compile
git clone https://github.com/semigodking/redsocks.git cd redsocks make
3. Confirm that gcc and make are installed
gcc --version make --version
If not installed:
apt install build-essential
4.Compile
If you run the make command directly to compile, the shadowsocks protocol will be supported by default and the HTTPS proxy will not be supported. For my intranet environment, redsocks2 only needs to be used with HTTP proxy (or socks5 proxy), so it does not need to support the shadowsocks protocol, and does not require HTTPS proxy, so you only need to run the following command:
make DISABLE_SHADOWSOCKS=true
If you also want to support HTTPS proxy, just run the following command:
make DISABLE_SHADOWSOCKS=true ENABLE_HTTPS_PROXY=true
Finally the compilation is successful:

After successful compilation, an executable file named redsocks2 will be generated, which can be viewed with the command:
ls -lh redsocks2
The output is as follows:

If the help information can be printed normally, it can be used normally:
./redsocks2 -h
The output is as follows:

Note: I do not recommend retaining the shadowsocks function module, because it will introduce additional encryption library dependencies (such as libsodium, mbedtls), increase compilation complexity and the chance of errors, especially if you do not intend to actually use it, it is completely meaningless (I wanted to keep the shadowsocks function at first, but it caused me so much trouble that I had to give up later~).
5.3 Create the "redsocks2.conf" configuration file
After the installation is complete, redsocks2 needs to create a configuration file "redsocks.conf". Assuming that the address of the proxy server is 192.168.1.1, the HTTP proxy service port is 8080, and the SOCKS5 proxy port is 1080, the configuration file content is as follows:
base { log_debug = off; log_info = on; log = stderr; daemon = off; redirector = iptables; } redsocks { // Listen to local TCP traffic bind = "0.0.0.0:12345"; // HTTP proxy server relay = "192.168.1.1:8080"; type = http-connect; login = ""; password = ""; } redudp { // Listen to local UDP traffic bind = "0.0.0.0:12346"; // The proxy server is socks5 (requires UDP support) relay = "192.168.1.1:1080"; type = socks5; login = ""; password = ""; // Required, for REDIRECT mode dest = "8.8.8.8:53"; udp_timeout = 30; udp_timeout_stream = 180; }
Configuration instructions:
- redsocks segment: responsible for proxy forwarding of TCP traffic.
- redudp segment: responsible for proxy forwarding of UDP traffic.
- bind = "0.0.0.0:12345": listens for TCP requests on port 12345 of all network cards in the LXC container
- relay = "192.168.1.1:8080": This is the address and port of the HTTP proxy
- type = http-relay: indicates that the target proxy is an HTTP proxy.
- bind = "0.0.0.0:12346": UDP request to port 12346 of all network cards of the LXC container.
- relay = "192.168.1.1:1080": This is the address and port of the SOCKS5 proxy
- type = socks5: indicates that the target proxy is a SOCKS5 proxy.
- dest = "8.8.8.8:53" is the destination address and port that the UDP module needs to specify. Even if it is only for transit purposes, it must be filled in. These two values will not be used in your actual traffic, but are only required to start redudp.
Note 1: The redsocks.conf configuration file and the redsocks2 executable file are both in the redsocks directory.
Note 2: I personally recommend that it is generally sufficient for the bypass gateway built with redsocks2 to support the TCP protocol. If you want to use the redudp segment to proxy the UDP protocol, you must use a SOCKS5 proxy, and the SOCKS5 proxy must support the UDP protocol (not all SOCKS5 proxies support the UDP protocol. For example, the SOCKS5 proxy provided by merlinclash does not support UDP by default. From this perspective, although redsocks2 supports UDP protocol proxy, it is still limited in its actual use. From this perspective, Proxifier is really awesome).
Note 3: As for DNS, it does not need to point to the bypass gateway. It is recommended to point directly to the main router (DNS hijacking needs to be configured on the main router). If it points to a commonly used domestic DNS server and the main router is not configured with DNS hijacking, then in this bypass gateway mode, you need to configure appropriate iptables and ebtables rules on the bypass gateway to redirect DNS requests to the main router (see the iptables section later in the article).
5.4 Run redsocks2
In the redsocks directory, just run the following command:
./redsocks2 -c redsocks.conf
Note 1: The "-c" parameter specifies the configuration file associated with redsocks2 when it is started.
5.5 Set redsocks2 to start automatically at boot
1. Create a systemd service unit file:
vim /etc/systemd/system/redsocks2.service
Paste the following content and save it (taking my environment as an example, I directly git redsocks2 to the root directory):
[Unit] Description=Redsocks2 Proxy Gateway After=network.target [Service] Type=simple ExecStart=/root/redsocks/redsocks2 -c /root/redsocks/redsocks.conf User=root Group=root WorkingDirectory=/root/redsocks Restart=always RestartSec=3 [Install] WantedBy=multi-user.target
- ExecStart: Set to the command you actually use to execute redsocks2, make sure the path is correct.
- WorkingDirectory: Set to the directory where redsocks2 is running. Make sure the redsocks.conf configuration file is also in the correct path.
- User and Group: Used to specify which user and group redsocks2 should run as. Avoid running it as the root user (don't learn from me). You can create a dedicated user for it (such as redsocks).
- Restart=always: If redsocks2 exits unexpectedly or crashes, it will be automatically restarted.
- RestartSec=3: Restart the process 3 seconds after a crash.
2. Reload the systemd configuration and enable the service:
systemctl daemon-reload systemctl enable redsocks2.service
3. Start redsocks2 service:
systemctl start redsocks2.service
4. Check service status:
systemctl status redsocks2.service
Normally, it will be displayed as follows:

6 Enable kernel IP forwarding
In Linux systems, net.ipv4.ip_forward controls the kernel's layer 3 forwarding capability. The default setting is 0, which prohibits IP packets from being forwarded between different interfaces. If you want the device to be used as a router, bypass gateway, or any transit node, you must turn it on. Otherwise, even if you configure iptables NAT (such as SNAT, DNAT) or REDIRECT rules, the data packets can only be processed locally and the forwarding link cannot be completed.
Temporary activation method:
echo 1 > /proc/sys/net/ipv4/ip_forward
In order to keep the effect after the system restart, /etc/sysctl.conf should be modified synchronously:
vim /etc/sysctl.conf
Find the following line:
#net.ipv4.ip_forward=1
Remove the comments and make sure it is = 1:

Then execute:
sysctl -p
Note: Failure to enable IP forwarding is one of the most common hidden problems in bypass proxy setup, so be sure to confirm it first during the debugging phase.
7 iptables configuration
The following is the iptables configuration adapted from the example redsocks2.conf in the previous article:
# Create a new chain iptables -t nat -N REDSOCKS # Exclude traffic on the local loopback interface (lo) iptables -t nat -A REDSOCKS -i lo -j RETURN # Exclude traffic whose destination address is the local IP (assuming the local IP is xxxx) iptables -t nat -A REDSOCKS -d xxxx -j RETURN # REDIRECT All other TCP traffic to local port 12345 iptables -t nat -A REDSOCKS -p tcp -j REDIRECT --to-ports 12345 # REDIRECT All other UDP traffic to local port 12346 (optional, for redudp) iptables -t nat -A REDSOCKS -p udp -j REDIRECT --to-ports 12346 # Apply REDSOCKS rules to PREROUTING (ingress packets) iptables -t nat -A PREROUTING -p tcp -j REDSOCKS iptables -t nat -A PREROUTING -p udp -j REDSOCKS ------------------------------------------------------------------------------ If the client's DNS points to the public DNS, you need to configure the following two rules: # Forward all UDP 53 DNS query traffic back to the primary router (assuming the main router mac address is 00:11:22:33:44:55) ebtables -t nat -A PREROUTING -p IPv4 --ip-proto udp --ip-dport 53 -j dnat --to-destination 00:11:22:33:44:55 # Perform source address NAT on the DNS query packets forwarded to the main router to ensure that the DNS response can return to the bypass gateway (assuming the bypass gateway's IP is xxxx) iptables -t nat -A POSTROUTING -p udp --dport 53 -j SNAT --to-source xxxx
Question: Why do we need to configure the last two rules (ebtables and iptables) on the bypass gateway when the client DNS is pointing to the public DNS? To answer this question, you need a little network knowledge.
You can use the following command to display a list of iptables rules with line numbers in the bypass gateway, which will help you locate a specific rule. :
iptables -t nat -L --line-numbers
I show here as follows:

You can use the following command to view the list of ebtables rules in the bypass gateway by table:
ebtables -t nat -L
I show here as follows:

In fact, it redirects all TCP traffic received by the bypass gateway to the local port 12345; forwards traffic with destination port UDP 53 directly to the main router and NATs the source address of the UDP packet to the address of the bypass gateway; redirects all other received UDP traffic to the local port 12346 (assuming the UDP proxy is configured, which I didn't configure anyway). It's very simple. At this point, the bypass gateway has been set up, and all devices that require global scientific capabilities only need to point the default gateway to the IP address of the redsocks2 deployment device (the DNS server can maintain its original settings, and it is no problem to point to the bypass gateway, but it is a bit redundant).
注1:iptables 和 ebtables 的配置,默认只是临时生效的,如果你不手动保存配置,重启后它们都会消失(因为 Linux 的网络堆栈初始化时不会自动还原你临时加的规则)。方法有几种,大家自己搜教程吧,懒得写了,不是本文的重点。
注2:实际部署时,为了兼顾简洁性和兼容性,我选择了不引入 ebtables,只通过 iptables 配置 TCP 透明代理,同时让 DNS 解析指向主路由,这样旁路由可以完全不处理UDP流量,简化了整体架构,可以放弃使用ebtables,好处在于运维更方便,只需要保存iptables的配置即可(可以使用iptables-persistent自动完成开机自动导入iptables配置)。
注3:虽然可以通过 ebtables 修改目标 MAC 地址,再结合 iptables 做 SNAT,从而让旁路网关完整接管设备发出的 UDP 流量,避免路由冲突,但这种方案在遇到像 Tailscale、ZeroTier 等自建隧道网络的应用时,仍然可能出现兼容性问题。这类应用通常依赖本地路由表或虚拟网卡管理出站流量,旁路网关的中间劫持反而会破坏其正常连接。因此,在部署旁路网关时,建议接入设备尽量保持干净,不安装此类特殊应用,以保证旁路方案的稳定性和一致性。
8 Conclusion
This article introduces how to use redsocks2 with HTTP proxy to build a lightweight, stable and high-performance bypass gateway. Strictly speaking, the solution built with redsocks2 + HTTP proxy cannot handle all types of network traffic. It is essentially aTransparent proxy gateway for HTTP/HTTPS trafficHowever, in most daily office or home environments, HTTP/HTTPS protocols usually account for 80% to 90% of TCP traffic for ordinary users. Therefore, even if this solution is only for HTTP/HTTPS, it can still cover most scientific Internet access needs, and the effect is close to "global proxy".
The advantages of this method are simple deployment and low resource usage. It is suitable for users who already have a main routing framework but want to perform global science on some devices, especially for friends who are unable or unwilling to use TUN/TProxy. It can provide an easy-to-maintain, migrate and recover solution (especially if there is an Apple TV, but it should be noted that all scientific Internet access software on Apple TV only provides HTTP proxy to the outside world).
Of course, this solution is not perfect. For example, UDP traffic relies on a SOCKS5 proxy that supports special forwarding, and many TCP applications (SSH, SMTP, IMAP, MySQL, Redis, RDP, WebSocket, etc.) are not ideally compatible with HTTP proxies. The most important thing is that a ready-made HTTP proxy is required.
In fact, specialized scientific software also has conditions for supporting UDP proxies, such as Merlinclash's description:


Poor AC-86U~, this is one of the reasons why I research bypass gateways: if it gets irritating me in the future, I will just switch to a scientific bypass gateway solution. It’s not supported now anyway, so it has no impact on me~.
If you have higher requirements for the transparent proxy capabilities of the bypass gateway (for example, you want to bypass the UDP protocol, or implement transparent forwarding of all TCP traffic), you can further expand on the basis of this article's solution, and combine tools such as tun2socks to convert the existing HTTP/SOCKS5 proxy traffic into transparent proxy access to achieve more complete traffic takeover. If you want to build a transparent proxy system with more complete functions and more detailed control, you can also consider using modern proxy platforms such as sing-box and Hysteria to rebuild an independent proxy environment.
But even without expansion, the redsocks2 + HTTP proxy mode shown in this article has achieved a good balance between usability, stability and simplicity. It is a solution that is worth trying first when deploying a bypass gateway in a home network, and it can already meet the needs of most people.
The following is a list of some common applications in bypass gateway mode, which support redsocks2's upper proxy as HTTP proxy or SOCKS5 proxy. It is fully sufficient for most people:
application | Upstream is HTTP proxy | Upstream is SOCKS5 proxy | Notes |
---|---|---|---|
apt | support | support | HTTP/HTTPS requests can be transparently proxied |
curl | support | support | Fully compatible with transparent proxy, no additional parameters required |
wget | support | support | The behavior is similar to curl. Some versions have unstable support for SOCKS but do not affect bypass mode. |
git (HTTPS protocol) | support | support | Issue HTTPS request, which can be taken over by redsocks2 |
git (SSH protocol) | Not supported | Not supported | The traffic sent is SSH protocol, not HTTP traffic, and cannot be transparently forwarded. |
ssh | Not supported | Not supported | Same as above, SSH protocol cannot be processed by redsocks2 |
Browser (such as Chrome) | support | support | Based on HTTP protocol communication, it can be completely transparent proxy, with good experience |
Electron applications (such as VSCode) | support | support | Use the system network stack, behave like a browser, transparent proxy is effective |
In order to intuitively show theredsocks2 + HTTP/SOCKS5 proxy"Solution, compared to the more common "Scientific Software + TProxy/TUN Transparent Proxy"I also made a comparison of the advantages and disadvantages of the two methods:
Compare Projects | redsocks2 + HTTP/SOCKS5 proxy | Scientific Software + TProxy/TUN Transparent Proxy |
---|---|---|
Deployment complexity | Low, only traffic forwarding and basic firewall rules need to be configured | Higher, requires in-depth understanding of TProxy/TUN mechanisms and complex firewall strategies |
Dependent Components | Only an existing HTTP/SOCKS5 proxy is required, no additional scientific software is required to run | Need to deploy and maintain a complete scientific software system over the long term |
System resource usage | Very low, redsocks2 itself is very lightweight, and resource overhead is negligible | Higher, scientific software operation itself brings certain CPU and memory consumption |
Functional coverage | Supports TCP traffic bypass, meeting most scientific needs | Supports full transparent bypass of TCP+UDP traffic, with more comprehensive functions |
stability | Very high, few components, simple forwarding logic, low error probability | Low, many components to run, long-term stability depends on scientific software |
Troubleshooting Difficulty | Low, clear troubleshooting path, simple and direct packet capture analysis | High, involving firewalls, routing tables, and software internal mechanisms, and the problem is complex |
Environmental adaptability | Powerful, only HTTP/SOCKS5 proxy is needed to run, suitable for various intranet environments | Generally, a relatively stable and open Linux environment is required, and the adaptability is limited |
Operation and maintenance costs | Very low, almost maintenance-free for a long time after deployment | Higher, need to pay attention to scientific software upgrades, rule updates and exception handling |
It can be seen that "redsocks2 + HTTP/SOCKS5 proxy" greatly reduces the deployment threshold and maintenance burden while maintaining availability and performance (if it is lightweight enough, the performance requirements are very small), which is very suitable for scenarios where you want to quickly and robustly build a bypass science gateway in the existing network environment (as long as there is an available HTTP/SOCKS5 proxy~). In general, each has its own applicable scenarios, but if the goal is to pursue lightweight, stable, low operation and maintenance costs, and hope to have better environmental universality, then the solution in this article is undoubtedly more advantageous.
It should be noted that although the solution introduced in this article finally presentsLightweight, stable, low latencyHowever, the process of achieving this result is not simple. During the construction process, you need to master iptables, ebtables The use of TCP/IP network basics, DNS query principle, HTTP/SOCKS5 protocol forwarding mechanism, containerization technology (such as LXC or virtual machine environment construction and management),as well as Linux system management, package manager usage, toolchain compilation and debugging capabilitiesAt the same time, in order to quickly locate the problem when it occurs, you also need to have certain troubleshooting skills, such as packet capture analysis, log checking, and route tracking.
In a sense, compared with directly using a more integrated and more user-friendly configuration wizardScientific Software + TProxy/TUN Transparent ProxyThe approach in this article, on the contrary, places higher demands on the underlying knowledge and self-configuration capabilities. It is this control over details that makes the bypass gateway built in the end not only lightweight and efficient, but also has good controllability and universality.
Therefore, if you want to obtain a truly lightweight, stable, and low-maintenance bypass gateway system through the methods in this article, it is recommended that you first have a certain understanding of the relevant basic knowledge before you start: this will not only make the construction process smoother, but also help with future maintenance and expansion.