How to Fix Trojan Port Blocked Issue: Simple Shell Script and NAT Forwarding Solutions

Recently, the 443 port of trojan is always blocked. I checked many articles online, and there are many ideas provided.

Here are a few summarized points:

  1. Disguise as a normal website and allow search engine crawlers to capture it.
  2. Nginx traffic splitting.
  3. Use CDN.
  4. Change the port.

Experimental Environment

  • centos 7
  • Using the one-click trojan setup script from https://github.com/Jrohy/trojan

Using iptables NAT Port Forwarding

From my current usage, trojan mostly gets its port blocked, the IP doesn’t seem to be a big problem. I’m too lazy to try the methods above, so I directly solve the problem with one iptables command.

 # Forward traffic from ports 40000~50000 to port 443

iptables -t nat -A PREROUTING -p tcp --dport 40000:50000 -j REDIRECT --to-ports 443   

Using NAT to forward traffic, it won’t listen to the port on the local machine, so you can’t see it with netstat.

After executing, the client can communicate with trojan using any port from 40000 to 50000.

Note: Many VPSs require port release in the console

Implementing “Pseudo-Dynamic Port” with Client Subscription Update

Write a

#!/bin/bash

# The generated subscription file is placed in the root directory of the website
filePath='~/www/vmess'

# Randomly generate a number between 40000 and 50000
randPort=$((RANDOM % 10000 + 40000 ))   

# Below is my trojan node information
echo -e \
"
trojan://[email protected]:443#HK1
trojan://[email protected]:443#HK3
trojan://[email protected]:443#HK0
trojan://[email protected]:443#JP1
" \
| sed "s/443/$randPort/g" | base64 > $filePath

# Write the node information with the changed port into the file after base64 encoding

This is a very simple shell script that replaces the original node information with a random number and then encodes it into a format acceptable to the client subscription using base64, and finally places this subscription in the website directory.

Crontab Scheduled Task to Update Subscription Node Information

Place the above script in the /usr/bin/ directory and add executable permissions.

[root@VM-4-13-centos ~]# chmod +x /usr/bin/vmess.sh 
[root@VM-4-13-centos ~]# crontab -l
1 * * * * /usr/bin/vmess.sh 

Client Subscription Addition

Here we take Shadowrocket as an example, others are similar.

trojan port blocked
trojan port blocked

OK, every time you refresh the subscription, it is a different port. The simplest way to achieve dynamic ports!

January 16, 2023 Supplement: One-Click Script for Automatic Subscription Update

Recently, many people added me as a friend and asked about configuration issues. So I wrote a one-click script to facilitate deployment for everyone.

cd /var/tmp/ && rm -f vmess.sh && wget https://zgao.top/download/vmess.sh && chmod +x vmess.sh

Then edit vmess.sh

Then execute

./vmess.sh

That’s it!