You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

共享主机已部署Express服务器,能否通过域名路径无端口访问?

共享主机上Express服务器的访问方案

核心结论

可以通过http://example.com/test-server形式访问你的Express服务器,无需带端口,只需调整代码和添加简单配置即可实现。

具体步骤

  1. 修改Express代码,添加路由前缀
    为了让服务响应/test-server路径的请求,需要给所有路由加上对应前缀,两种方式任选:

    • 方式一:使用路由挂载
      const express = require('express')
      const app = express()
      const port = 8080
      
      // 创建路由实例并挂载到/test-server前缀
      const apiRouter = express.Router()
      apiRouter.get('/', (req, res) => {
        res.send('Hello World!')
      })
      // 可添加更多路由到apiRouter
      app.use('/test-server', apiRouter)
      
      app.listen(port, () => {
        console.log(`Example app listening on port ${port}`)
      })
      
    • 方式二:直接修改路由路径
      const express = require('express')
      const app = express()
      const port = 8080
      
      app.get('/test-server', (req, res) => {
        res.send('Hello World!')
      })
      
      app.listen(port, () => {
        console.log(`Example app listening on port ${port}`)
      })
      
  2. 添加.htaccess反向代理规则
    共享主机默认的Web服务器(大多为Apache)会拦截80/443端口的请求,需要通过.htaccess将/test-server路径的请求转发到本地8080端口的Express服务:
    在网站根目录(通常是/var/www/html,不确定可咨询主机商)创建或编辑.htaccess文件,写入以下内容:

    RewriteEngine On
    # 将/test-server开头的请求转发到本地Express服务
    RewriteRule ^test-server/(.*)$ http://localhost:8080/test-server/$1 [P,L]
    # 匹配/test-server根路径(不带子路径)的请求
    RewriteRule ^test-server$ http://localhost:8080/test-server [P,L]
    
  3. 后台运行Express服务
    共享主机的终端会话关闭后,前台进程会终止,需用pm2管理进程保持服务运行:

    • 安装pm2:npm install -g pm2
    • 进入项目目录:cd /var/www/test-server
    • 启动服务:pm2 start app.js --name "test-server"
    • 保存进程配置:pm2 save,确保主机重启后服务自动启动

无法访问的原因说明

共享主机通常会限制外部直接访问非80/443的端口,所以即使Express服务在8080端口正常启动,外部也无法通过example.com:8080访问。通过默认Web服务器的反向代理,就能将80端口的请求转发到本地Express服务,实现无端口访问。

内容的提问来源于stack exchange,提问作者Dipen Chand

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 17:25:26