Preface
OpenAI Codex CLI brings an AI-assisted coding workflow directly into the terminal. Instead of switching between an editor, a browser, and a chat window, developers can ask Codex to inspect files, explain code, propose changes, and help execute development tasks from a command-line interface. For users in China, however, the quality of this workflow depends heavily on network routing. A terminal may appear to be connected while API requests time out, authentication fails, or responses arrive so slowly that the tool becomes difficult to use.
Clash can solve many of these problems by routing selected Codex traffic through a suitable proxy node while leaving ordinary domestic traffic on the direct connection. This is usually more reliable than sending every application through a remote server. It also gives you clear control over DNS behavior, system proxy settings, TUN mode, and rule-based routing.
This guide explains how to prepare Clash for Codex CLI on Windows, macOS, or Linux. It focuses on practical configuration rather than a particular Clash graphical client. The menus may look different in Clash Verge Rev, Mihomo Party, or another frontend, but the underlying concepts and YAML options are broadly similar.
Technical Goal
Route Codex CLI API traffic through a stable Clash proxy, prevent DNS and shell environment mistakes, and keep local services fast through split tunneling.
1Prepare Clash and Codex CLI
Clash is a traffic controller, not a proxy subscription provider. Before changing any rules, you need a working profile containing at least one usable node and a policy group that can select it. A node with a low latency result is not automatically the best choice for an AI API. Stability, IP reputation, packet loss, and sustained response speed matter more than a single ping measurement.
Install a maintained Clash client that supports the Mihomo core or another compatible modern core. Import your subscription through the client’s normal Profiles or Subscriptions page, update the profile, and select a node manually first. Do not begin troubleshooting Codex with an untested automatic group, because a health-check algorithm may select a node that responds to a ping but performs poorly for long HTTPS requests.
- Update Clash and its profile before testing. An outdated core may not understand newer rule or DNS fields.
- Choose a node in a supported region with consistent latency rather than selecting only the cheapest or fastest-looking option.
- Confirm that the Clash system proxy is enabled, or prepare to use TUN mode for command-line programs that ignore system proxy variables.
- Open a new terminal after changing environment variables so the shell inherits the latest settings.
- Keep your API key private. Never place it in a public YAML profile, screenshot, repository, or shell history that will be shared.
Codex CLI itself usually communicates through HTTPS. That means the first test should focus on TCP and TLS connectivity, not UDP. If your Clash client has separate switches for system proxy, enhanced mode, and TUN, change one item at a time and test after each change. This makes it much easier to identify whether a failure comes from the core, the profile, the operating system, or Codex.
Check the local Clash port
Open Clash’s settings and note the HTTP or mixed port. Common examples include 7890 or 7897, but you should always use the value shown by your own client. The HTTP port is useful for shell variables and tools that understand standard proxy URLs. A mixed port can accept both HTTP and SOCKS-style connections, depending on the client configuration.
A successful HTTP response, an authentication-related response, or even a clear server error can indicate that the request reached the remote service. A connection refusal means that the local port is wrong, Clash is not running, or the selected listener is disabled. This test does not prove that Codex is fully configured, but it separates basic proxy connectivity from application-level problems.
2Configure the Terminal Proxy
Graphical applications often read the operating system proxy automatically. Terminal programs are less predictable. Some read HTTP_PROXY and HTTPS_PROXY; some prefer lowercase variables; others ignore them completely. For that reason, configure both uppercase and lowercase forms, then verify the result in the same shell where you will launch Codex.
Temporary variables for one session
On macOS or Linux, the following commands apply the proxy to the current shell session. They do not permanently modify your computer and disappear when the terminal closes.
HTTPS_PROXY does not mean that the proxy listener itself must use HTTPS. It tells the client which proxy to use when accessing an HTTPS destination. If your Clash listener is a local HTTP proxy, the value should normally begin with http://. Using https://127.0.0.1 against an HTTP listener is a common mistake and produces TLS or handshake errors.
On Windows PowerShell, use environment variables in the current process with the following syntax:
Some command-line tools honor NO_PROXY. This variable prevents local destinations from being sent through Clash. It is useful for local development servers, package registries on your private network, and services such as localhost. Avoid adding broad domains to NO_PROXY until you understand the effect, because an overly wide bypass list can accidentally send Codex-related traffic direct.
Pro Tip: Verify Before Blaming Codex
Run a simple HTTPS request with the same shell variables before launching Codex. If curl cannot connect through Clash, reinstalling the CLI will not solve the underlying routing problem.
Make the setting persistent carefully
If the temporary test works, you may add the exports to ~/.zshrc, ~/.bashrc, or your PowerShell profile. Persistent proxy variables are convenient, but they can surprise you later when a package manager, Git command, or internal company tool unexpectedly uses the proxy. A safer approach is to create a small shell function or a project-specific launcher that enables the variables only when you need Codex.
Whether this wrapper works depends on how the installed Codex CLI is invoked and which proxy variables its underlying runtime supports. If the application ignores these variables, use Clash TUN mode or the client’s process-level routing feature instead of assuming the wrapper is active.
3Route Codex Traffic with Clash Rules
Rule mode is usually the best starting point. It allows AI service traffic to use a proxy while domestic websites, local development tools, and private addresses remain direct. The exact service domains used by Codex can change over time, so avoid relying on one hostname alone. Start with the documented API domains and inspect Clash’s connection log while Codex is running.
In a YAML profile, place specific rules before broad catch-all rules. The final rule in many profiles is MATCH, which handles everything not matched earlier. If an OpenAI rule is placed after MATCH, it will never be reached.
Here, AI must be the name of an existing proxy policy group in your profile. If your subscription uses a group called Proxy, Auto, or 🚀 Proxy, replace AI with that exact name. YAML indentation is significant, and a malformed profile may fail to load altogether. Always validate or preview the configuration in your client before applying it.
Important Routing Note
Do not copy a domain list blindly from an old tutorial. Use Clash’s connection panel to see the actual destination, and add only domains that are necessary for your workflow. Routing every domain through a distant node can increase latency and expose unrelated traffic.
DNS settings and fake-IP mode
DNS behavior can determine whether a rule matches correctly. With ordinary redirection, a local resolver may answer a domain before Clash can apply the intended policy. In environments where DNS hijacking or inconsistent resolution is common, Mihomo’s enhanced DNS mode can provide more predictable results.
Do not paste this block into a profile without checking compatibility. Some managed subscriptions control the DNS section, and some clients use different fields. Also review the fake-IP filter list. Local banking sites, corporate intranets, printers, and certain game launchers may require real IP resolution or direct routing. If a local service breaks after enabling fake-IP, add a targeted exception rather than disabling all DNS handling.
When TUN mode is necessary
Environment variables are lightweight, but they work only when the application honors them. TUN mode creates a virtual network interface and allows Clash to capture traffic from programs that do not understand HTTP proxy settings. This can be helpful when Codex is started by an editor, a task runner, or a child process that does not inherit your shell environment.
Enable TUN only after confirming that the core has permission to create the interface. On Windows, this may require administrator approval. On macOS or Linux, the client may request elevated privileges. Start with rule mode, then enable TUN if the Clash log shows no Codex connections despite a working command-line proxy test. Keep local network and private IP bypass rules enabled so that Docker, SSH, file sharing, and development servers continue to work.
4Test the Workflow and Troubleshoot Failures
Testing should proceed from the bottom of the network stack upward. First confirm that Clash is listening. Next confirm that a simple HTTPS request uses the intended node. Then verify DNS and rule matches in the Clash log. Only after those checks should you investigate Codex authentication, permissions, or project configuration.
- Connection refused: Check that Clash is running and that the port in your proxy variables matches the active HTTP or mixed listener.
- Timeouts: Try another node, inspect packet loss, and check whether the selected policy group is switching nodes too frequently.
- TLS or certificate errors: Confirm that you used
http://for a local HTTP listener. Avoid disabling certificate verification as a first response. - Codex ignores the proxy: Check the application documentation, launch it from the same shell, or use TUN mode for traffic capture.
- Authentication loops: Remove stale credentials only through the CLI’s documented logout or reset process, and verify that system time is correct.
- Very slow first response: Compare several nodes and watch for DNS delays, overloaded servers, or a policy group that is selecting a distant route.
- Local tools stop working: Review
NO_PROXY, private IP rules, fake-IP filters, and TUN bypass settings.
Read the Clash connection log
The connection log is more useful than guessing from a generic terminal error. Start Codex, then look for the destination host, the selected rule, the policy group, and the node actually used. A request marked DIRECT when you expected AI indicates a rule-order or DNS-matching issue. A request that reaches the correct group but fails repeatedly suggests a node, TLS, or upstream service problem.
Use a minimal project for the first test. Avoid running a large repository scan, installing packages, or modifying production files while the network path is still uncertain. Ask Codex for a harmless task such as listing a directory or explaining a small local file. Once the response is stable, test a real API-assisted workflow and monitor whether long requests remain connected.
- Store credentials in the CLI’s supported secure storage or environment mechanism, not inside a Clash profile.
- Do not paste private source code, tokens, customer data, or proprietary logs into an AI prompt unless your organization permits it.
- Pin a stable Clash profile version before an important coding session, and export a backup before editing YAML.
- Use separate proxy policy groups for AI services and general browsing when you need different nodes or limits.
- Stop and review unexpected connections in Clash rather than adding increasingly broad domain rules.
Remember that a proxy can improve reachability but cannot repair an invalid account, an unsupported service region, an expired credential, or a broken Codex installation. Separate network symptoms from application symptoms by testing the same endpoint with curl and by checking the CLI’s own diagnostic output.
Frequently Asked Questions
Should I use Global Mode for Codex CLI?
Global Mode can be useful as a short diagnostic test because it removes most rule-matching uncertainty. It is not always the best permanent setup. Once you confirm that the selected node works, switch back to Rule Mode and route only the required AI and supporting domains. This reduces latency for domestic services and prevents unrelated traffic from leaving through the proxy.
Why does Codex work in my browser but fail in the terminal?
Browsers may use the system proxy, an extension, or a client-side tunnel, while the terminal process may have no proxy configuration at all. The browser and CLI can therefore use completely different routes. Check shell variables, launch context, and the Clash log. If the CLI is started by an editor, verify whether that editor inherits the same environment.
Is TUN mode better than HTTP proxy variables?
Neither is universally better. HTTP variables are simple, transparent, and easy to disable. TUN mode is more comprehensive and can capture applications that ignore proxy variables, but it requires additional permissions and can interfere with local networking if configured carelessly. Use the least invasive method that reliably captures your Codex traffic.
What should I do when one node works briefly and then stops?
Check whether the node is overloaded, has unstable packet loss, or is being rotated by an automatic policy group. Select a stable node manually, retest with curl, and inspect the connection log. If several nodes fail at the same time, investigate DNS, credentials, or a service-side issue rather than repeatedly changing servers.
With a maintained Clash client, a carefully ordered rule set, correctly scoped terminal variables, and a stable node, Codex CLI can become a practical part of a daily development workflow in China. Make one change at a time, keep credentials separate from network configuration, and use logs to verify every assumption.