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

Ubuntu22.04+Apache2.4.52:如何将.NET Core API部署在/api子目录并根目录运行Nuxt3

配置修改方案

核心思路

通过Apache的路径匹配规则,将/api开头的请求代理到.NET Core API(http://127.0.0.1:5000),根路径/的请求代理到Nuxt3应用(http://localhost:3000)。代理规则顺序很重要,需先定义更具体的/api规则,再定义根路径规则。


1. 修改非SSL配置(80端口)

替换/etc/apache2/sites-available下的非SSL配置文件内容:

<VirtualHost *:*>
    RequestHeader set "X-Forwarded-Proto" expr=%{REQUEST_SCHEME}s
</VirtualHost>

<VirtualHost *:80>
    ProxyPreserveHost On
    # 匹配/api路径,代理到.NET Core API
    ProxyPass /api http://127.0.0.1:5000/api
    ProxyPassReverse /api http://127.0.0.1:5000/api
    # 根路径代理到Nuxt3应用
    ProxyPass / http://localhost:3000/
    ProxyPassReverse / http://localhost:3000/

    ServerName mydomain.test
    Header set Access-Control-Allow-Origin "*"
    Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
    Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    # 保留HTTPS跳转规则
    RewriteEngine on
    RewriteCond %{SERVER_NAME} =mydomain.test
    RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

2. 修改SSL配置(443端口)

替换带-l-ssl后缀的SSL配置文件内容:

<IfModule mod_ssl.c>
    <VirtualHost *:443>
        ProxyPreserveHost On
        # 匹配/api路径,代理到.NET Core API
        ProxyPass /api http://127.0.0.1:5000/api
        ProxyPassReverse /api http://127.0.0.1:5000/api
        # 根路径代理到Nuxt3应用
        ProxyPass / http://localhost:3000/
        ProxyPassReverse / http://localhost:3000/

        ServerName mydomain.test
        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        Include /etc/letsencrypt/options-ssl-apache.conf
        SSLCertificateFile /etc/letsencrypt/live/mydomain.test/fullchain.pem
        SSLCertificateKeyFile /etc/letsencrypt/live/mydomain.test/privkey.pem
    </VirtualHost>
</IfModule>

3. 关键注意事项

  • 配置.NET Core API的BasePath:在API的Program.cs中添加路径前缀,确保接口能正确响应/api开头的请求,示例代码:
    var builder = WebApplication.CreateBuilder(args);
    // 设置API的基础路径
    app.UsePathBase("/api");
    
    重启.NET Core API服务生效。
  • 确认Apache模块已启用:确保mod_proxy、mod_proxy_http、mod_headers模块启用,执行命令:
    sudo a2enmod proxy proxy_http headers rewrite
    
  • 重启Apache服务:配置修改后执行以下命令使配置生效:
    sudo systemctl restart apache2
    
  • 验证Nuxt3应用:确保Nuxt3应用在http://localhost:3000正常运行,无路径冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 05:24:52