[GH-ISSUE #4561] [Bug]: API endpoints are inaccessible after configuring reverse proxy #3127

Closed
opened 2026-10-31 20:30:16 +07:00 by bsakaguchi · 4 comments
Owner

Originally created by @Aurora211 on GitHub (May 25, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/4561

Describe the bug

When I used Python to try to obtain and set XRay configuration using Token according to the API documentation, I found that almost all API endpoints were inaccessible, all returning 404. I used Fiddler to capture and analyze the packets sent by Python and found no issues—they fully complied with the documentation requirements.

How to reproduce the problem

  1. Install 3XUI using Docker
  2. Configure OpenResty reverse proxy to take over port 2053
  3. Use Python or other tools to access the API interface

Expected behavior

When accessing /panel/xray/ using the POST method, the Xray configuration information should be returned

Actual behavior

The API returned an HTTP 404 error with no explanation

Relevant logs


Screenshots

No response

3x-ui version

3.0.2

Xray-core version

26.4.25

How did you install 3x-ui?

Docker / Docker Compose

Operating system

Ubuntu 24.04

Which parts of the panel are affected?

Backend (API endpoints, login, settings)

Browser (only if it is a UI bug)

This is not a UI bug

Is the panel behind a reverse proxy or CDN?

Yes — other

Before submitting

  • I searched existing issues and this bug has not been reported.
  • I am running the latest released version of 3x-ui (or have verified the bug still exists on it).
  • This bug report is written in English.
  • I have redacted any sensitive data (tokens, real domains, client UUIDs).
Originally created by @Aurora211 on GitHub (May 25, 2026). Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/4561 ### Describe the bug When I used Python to try to obtain and set XRay configuration using Token according to the API documentation, I found that almost all API endpoints were inaccessible, all returning 404. I used Fiddler to capture and analyze the packets sent by Python and found no issues—they fully complied with the documentation requirements. ### How to reproduce the problem 1. Install 3XUI using Docker 2. Configure OpenResty reverse proxy to take over port 2053 3. Use Python or other tools to access the API interface ### Expected behavior When accessing `/panel/xray/` using the POST method, the Xray configuration information should be returned ### Actual behavior The API returned an HTTP 404 error with no explanation ### Relevant logs ```shell ``` ### Screenshots _No response_ ### 3x-ui version 3.0.2 ### Xray-core version 26.4.25 ### How did you install 3x-ui? Docker / Docker Compose ### Operating system Ubuntu 24.04 ### Which parts of the panel are affected? Backend (API endpoints, login, settings) ### Browser (only if it is a UI bug) This is not a UI bug ### Is the panel behind a reverse proxy or CDN? Yes — other ### Before submitting - [x] I searched [existing issues](../issues?q=is%3Aissue) and this bug has not been reported. - [x] I am running the latest released version of 3x-ui (or have verified the bug still exists on it). - [x] This bug report is written in English. - [x] I have redacted any sensitive data (tokens, real domains, client UUIDs).
bsakaguchi 2026-10-31 20:30:16 +07:00
  • closed this issue
  • added the
    bug
    label
Author
Owner

@StreetStrider commented on GitHub (Jun 21, 2026):

I experience this on ghcr.io/mhsanaei/3x-ui:3.3.1. Can someone please explain what's happening here, is it a proper behavior or a bug? I'm seeing 404 on any API path. Cannot use API. @MHSanaei @Aurora211

<!-- gh-comment-id:4761925774 --> @StreetStrider commented on GitHub (Jun 21, 2026): I experience this on `ghcr.io/mhsanaei/3x-ui:3.3.1`. Can someone please explain what's happening here, is it a proper behavior or a bug? I'm seeing 404 on any API path. Cannot use API. @MHSanaei @Aurora211
Author
Owner

@Aurora211 commented on GitHub (Jun 22, 2026):

I experience this on ghcr.io/mhsanaei/3x-ui:3.3.1. Can someone please explain what's happening here, is it a proper behavior or a bug? I'm seeing 404 on any API path. Cannot use API. @MHSanaei @Aurora211

I can not fix the problem. All api endpoints which using token authorization is returning 404 error. But you can use Username and Password authorization to access the api you need. Remember to request for CSRF token and add it into your request header.@StreetStrider

<!-- gh-comment-id:4766506418 --> @Aurora211 commented on GitHub (Jun 22, 2026): > I experience this on `ghcr.io/mhsanaei/3x-ui:3.3.1`. Can someone please explain what's happening here, is it a proper behavior or a bug? I'm seeing 404 on any API path. Cannot use API. [@MHSanaei](https://github.com/MHSanaei) [@Aurora211](https://github.com/Aurora211) I can not fix the problem. All api endpoints which using token authorization is returning 404 error. But you can use Username and Password authorization to access the api you need. Remember to request for CSRF token and add it into your request header.@StreetStrider
Author
Owner

@StreetStrider commented on GitHub (Jun 22, 2026):

@Aurora211 I'm using username/password scenario and also see 404. I'm automating inside container, so CSRF should not be a problem. I'm using username/password and not token because it is what allow me to create fully un-attended install with predefined inbounds/clients.

@MHSanaei Is it possible to re-open?

<!-- gh-comment-id:4767458137 --> @StreetStrider commented on GitHub (Jun 22, 2026): @Aurora211 I'm using username/password scenario and also see 404. I'm automating inside container, so CSRF should not be a problem. I'm using username/password and not token because it is what allow me to create fully un-attended install with predefined inbounds/clients. @MHSanaei Is it possible to re-open?
Author
Owner

@Aurora211 commented on GitHub (Sep 4, 2026):

@StreetStrider You can refer to the method I wrote for logging in with a username and password along with CSRF. This program is used to access the 3xui application located inside the docker container. It can properly implement the login functionality. You can ignore classes such as XrayAPI loaded from .types; they are my methods for parsing data.

import json
import logging
import requests
import threading
from typing import Dict, Tuple

from .types import (
    XrayApi,
    XrayLog,
    XrayRule,
    XrayStats,
    XrayPolicy,
    XrayInbound,
    XrayMetrics,
    XrayRouting,
    XraySetting,
    XrayBalancer,
    XrayOutbound,
    XrayObservatory,
)

logger: logging.Logger = logging.getLogger("3XUI-SubscriptionUpdate.XUI")

class XUI:
    def __init__(
            self,
            base_url: str,
            username: str,
            password: str,
            verify:   bool = True,
    ) -> None:
        """
        创建3XUI Xray设置管理器

        Args:
            base_url (str):  3XUI API地址
            username (str):  3XUI 用户名
            password (str):  3XUI 密码
            verify   (bool): 是否验证SSL证书
        """
        self.base_url: str = base_url
        self.username: str = username
        self.password: str = password

        # 3XUI会话
        self.session:      requests.Session = self.__create_new_session__(verify=verify)
        self.session_lock: threading.RLock  = threading.RLock()
    
    def __create_new_session__(self, verify: bool = True) -> requests.Session:
        """
        创建新的3XUI会话

        Args:
            verify (bool): 是否验证SSL证书

        Returns:
            requests.Session: 新的3XUI会话
        """
        # 创建会话
        session: requests.Session = requests.Session()
        session.headers.update({
            "Accept": "application/json",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36"
        })
        if not verify:
            session.verify = False
        logger.debug(f"3XUI 会话创建完成")
        return session
    def __update_csrf_token__(self) -> None:
        """
        更新3XUI会话CSRF Token
        """
        with self.session_lock:
            # 获取CSRF Token
            response: requests.Response = self.session.get(f"{self.base_url}/csrf-token")
            try:
                response.raise_for_status()

                csrf_token: str = response.json()["obj"]
                self.session.headers.update({"X-CSRF-Token": csrf_token})
            except requests.exceptions.HTTPError as e:
                logger.critical(f"3XUI 会话创建失败(HTTP {response.status_code})")
                raise e
            except KeyError as e:
                logger.critical(f"3XUI 会话创建失败(JSON相应不包含obj)")
                raise e
            except Exception as e:
                logger.critical(f"3XUI 会话创建失败(未知错误)")
                raise e
            logger.info(f"3XUI 会话 CSRF Token 更新成功({csrf_token})")
    
    def login(self, two_factor_code: str = "") -> bool:
        with self.session_lock:
            self.__update_csrf_token__()

            response: requests.Response = self.session.post(
                f"{self.base_url}/login",
                json={"username": self.username, "password": self.password, "twoFactorCode": two_factor_code}
            )
            try:
                response.raise_for_status()

                success: bool = response.json()["success"]
            except requests.exceptions.HTTPError as e:
                logger.critical(f"3XUI 登录失败(HTTP {response.status_code})")
                return False
            except KeyError as e:
                logger.critical(f"3XUI 登录失败(JSON相应不包含success)")
                return False
            except Exception as e:
                logger.critical(f"3XUI 登录失败(未知错误)")
                return False
        
            if success == True:
                logger.info("3XUI 登录成功")
                return True
            else:
                logger.critical("3XUI 登录失败")
                return False
    def xray(self) -> XraySetting:
        """
        获取3XUI Xray设置

        Returns:
            Dict: 3XUI Xray设置
        """
        with self.session_lock:
            response: requests.Response = self.session.post(
                f"{self.base_url}/panel/api/xray",
            )
            try:
                response.raise_for_status()
                v: Dict = json.loads(response.json()["obj"])
                if "xraySetting" not in v:
                    raise KeyError("JSON相应不包含xraySetting")
                setting: XraySetting = XraySetting.from_dict(v["xraySetting"])
                return setting
            except requests.exceptions.HTTPError as e:
                logger.critical(f"获取3XUI Xray设置失败(HTTP {response.status_code})")
                raise e
            except KeyError as e:
                logger.critical(f"获取3XUI Xray设置失败({e})")
                raise e
            except Exception as e:
                logger.critical(f"获取3XUI Xray设置失败(未知错误)")
                raise e
    def status(self) -> Tuple[bool, Dict]:
        """
        获取3XUI状态

        Returns:
            bool: 3XUI处理状态
            Dict: 3XUI状态
        """
        with self.session_lock:
            response: requests.Response = self.session.get(
                f"{self.base_url}/panel/api/server/status",
            )
            try:
                response.raise_for_status()
                return (response.json()["success"], response.json()["obj"])
            except requests.exceptions.HTTPError as e:
                logger.critical(f"获取3XUI状态失败(HTTP {response.status_code})")
                return (False, {})
            except KeyError as e:
                logger.critical(f"获取3XUI状态失败({e})")
                raise e
            except Exception as e:
                logger.critical(f"获取3XUI状态失败(未知错误)")
                raise e
    def update(self, data: XraySetting, outboundTestUrl: str) -> bool:
        """
        更新3XUI Xray设置

        Returns:
            bool: 更新结果
        """
        with self.session_lock:
            response: requests.Response = self.session.post(
                f"{self.base_url}/panel/api/xray/update",
                data={
                    "xraySetting":     json.dumps(data.to_dict()),
                    "outboundTestUrl": outboundTestUrl
                },
            )
            try:
                response.raise_for_status()

                success: bool = response.json()["success"]
                if success:
                    return True
                else:
                    return False
            except requests.exceptions.HTTPError as e:
                logger.critical(f"3XUI Xray设置更新失败(HTTP {response.status_code})")
                return False
            except KeyError as e:
                logger.critical(f"3XUI Xray设置更新失败({e})")
                return False
            except Exception as e:
                logger.critical(f"3XUI Xray设置更新失败({e})")
                return False
    def restart_xray_core(self) -> bool:
        """
        重启3XUI Xray Core

        Returns:
            bool: 重启结果
        """
        with self.session_lock:
            response: requests.Response = self.session.post(
                f"{self.base_url}/panel/api/server/restartXrayService",
            )
            try:
                response.raise_for_status()

                success: bool = response.json()["success"]
                if success:
                    return True
                else:
                    return False
            except requests.exceptions.HTTPError as e:
                logger.critical(f"3XUI Xray Core重启失败(HTTP {response.status_code})")
                return False
            except KeyError as e:
                logger.critical(f"3XUI Xray Core重启失败({e})")
                return False
            except Exception as e:
                logger.critical(f"3XUI Xray Core重启失败({e})")
                return False
<!-- gh-comment-id:5535520475 --> @Aurora211 commented on GitHub (Sep 4, 2026): @StreetStrider You can refer to the method I wrote for logging in with a username and password along with CSRF. This program is used to access the 3xui application located inside the docker container. It can properly implement the login functionality. You can ignore classes such as XrayAPI loaded from `.types`; they are my methods for parsing data. ```python import json import logging import requests import threading from typing import Dict, Tuple from .types import ( XrayApi, XrayLog, XrayRule, XrayStats, XrayPolicy, XrayInbound, XrayMetrics, XrayRouting, XraySetting, XrayBalancer, XrayOutbound, XrayObservatory, ) logger: logging.Logger = logging.getLogger("3XUI-SubscriptionUpdate.XUI") class XUI: def __init__( self, base_url: str, username: str, password: str, verify: bool = True, ) -> None: """ 创建3XUI Xray设置管理器 Args: base_url (str): 3XUI API地址 username (str): 3XUI 用户名 password (str): 3XUI 密码 verify (bool): 是否验证SSL证书 """ self.base_url: str = base_url self.username: str = username self.password: str = password # 3XUI会话 self.session: requests.Session = self.__create_new_session__(verify=verify) self.session_lock: threading.RLock = threading.RLock() def __create_new_session__(self, verify: bool = True) -> requests.Session: """ 创建新的3XUI会话 Args: verify (bool): 是否验证SSL证书 Returns: requests.Session: 新的3XUI会话 """ # 创建会话 session: requests.Session = requests.Session() session.headers.update({ "Accept": "application/json", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36" }) if not verify: session.verify = False logger.debug(f"3XUI 会话创建完成") return session def __update_csrf_token__(self) -> None: """ 更新3XUI会话CSRF Token """ with self.session_lock: # 获取CSRF Token response: requests.Response = self.session.get(f"{self.base_url}/csrf-token") try: response.raise_for_status() csrf_token: str = response.json()["obj"] self.session.headers.update({"X-CSRF-Token": csrf_token}) except requests.exceptions.HTTPError as e: logger.critical(f"3XUI 会话创建失败(HTTP {response.status_code})") raise e except KeyError as e: logger.critical(f"3XUI 会话创建失败(JSON相应不包含obj)") raise e except Exception as e: logger.critical(f"3XUI 会话创建失败(未知错误)") raise e logger.info(f"3XUI 会话 CSRF Token 更新成功({csrf_token})") def login(self, two_factor_code: str = "") -> bool: with self.session_lock: self.__update_csrf_token__() response: requests.Response = self.session.post( f"{self.base_url}/login", json={"username": self.username, "password": self.password, "twoFactorCode": two_factor_code} ) try: response.raise_for_status() success: bool = response.json()["success"] except requests.exceptions.HTTPError as e: logger.critical(f"3XUI 登录失败(HTTP {response.status_code})") return False except KeyError as e: logger.critical(f"3XUI 登录失败(JSON相应不包含success)") return False except Exception as e: logger.critical(f"3XUI 登录失败(未知错误)") return False if success == True: logger.info("3XUI 登录成功") return True else: logger.critical("3XUI 登录失败") return False def xray(self) -> XraySetting: """ 获取3XUI Xray设置 Returns: Dict: 3XUI Xray设置 """ with self.session_lock: response: requests.Response = self.session.post( f"{self.base_url}/panel/api/xray", ) try: response.raise_for_status() v: Dict = json.loads(response.json()["obj"]) if "xraySetting" not in v: raise KeyError("JSON相应不包含xraySetting") setting: XraySetting = XraySetting.from_dict(v["xraySetting"]) return setting except requests.exceptions.HTTPError as e: logger.critical(f"获取3XUI Xray设置失败(HTTP {response.status_code})") raise e except KeyError as e: logger.critical(f"获取3XUI Xray设置失败({e})") raise e except Exception as e: logger.critical(f"获取3XUI Xray设置失败(未知错误)") raise e def status(self) -> Tuple[bool, Dict]: """ 获取3XUI状态 Returns: bool: 3XUI处理状态 Dict: 3XUI状态 """ with self.session_lock: response: requests.Response = self.session.get( f"{self.base_url}/panel/api/server/status", ) try: response.raise_for_status() return (response.json()["success"], response.json()["obj"]) except requests.exceptions.HTTPError as e: logger.critical(f"获取3XUI状态失败(HTTP {response.status_code})") return (False, {}) except KeyError as e: logger.critical(f"获取3XUI状态失败({e})") raise e except Exception as e: logger.critical(f"获取3XUI状态失败(未知错误)") raise e def update(self, data: XraySetting, outboundTestUrl: str) -> bool: """ 更新3XUI Xray设置 Returns: bool: 更新结果 """ with self.session_lock: response: requests.Response = self.session.post( f"{self.base_url}/panel/api/xray/update", data={ "xraySetting": json.dumps(data.to_dict()), "outboundTestUrl": outboundTestUrl }, ) try: response.raise_for_status() success: bool = response.json()["success"] if success: return True else: return False except requests.exceptions.HTTPError as e: logger.critical(f"3XUI Xray设置更新失败(HTTP {response.status_code})") return False except KeyError as e: logger.critical(f"3XUI Xray设置更新失败({e})") return False except Exception as e: logger.critical(f"3XUI Xray设置更新失败({e})") return False def restart_xray_core(self) -> bool: """ 重启3XUI Xray Core Returns: bool: 重启结果 """ with self.session_lock: response: requests.Response = self.session.post( f"{self.base_url}/panel/api/server/restartXrayService", ) try: response.raise_for_status() success: bool = response.json()["success"] if success: return True else: return False except requests.exceptions.HTTPError as e: logger.critical(f"3XUI Xray Core重启失败(HTTP {response.status_code})") return False except KeyError as e: logger.critical(f"3XUI Xray Core重启失败({e})") return False except Exception as e: logger.critical(f"3XUI Xray Core重启失败({e})") return False ```
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#3127
No description provided.