首页
/ Mercure项目在Nginx反向代理下的配置指南

Mercure项目在Nginx反向代理下的配置指南

2025-06-11 20:09:53作者:晏闻田Solitary

前言

Mercure是一个基于Server-Sent Events(SSE)技术的实时通信协议实现,它允许服务器向客户端推送实时更新。本文将详细介绍如何在生产环境中配置Mercure服务,特别是当它运行在Nginx反向代理之后时的最佳实践。

环境准备

在开始配置前,我们需要明确几个关键组件:

  1. Mercure服务本身(本文使用二进制版本而非Docker)
  2. Nginx作为反向代理
  3. 后端服务(如Symfony应用)
  4. 前端应用(如Vue.js)

基础配置

系统环境变量

首先设置系统环境变量,这些变量将被Mercure服务使用:

# /etc/environment
MERCURE_PUBLISHER_JWT_KEY="yourPublisherKey"
MERCURE_SUBSCRIBER_JWT_KEY="yourSubscriberKey"
SERVER_NAME=http://localhost
MERCURE_PUBLIC_URL=https://mercure.yourdomain.com/.well-known/mercure

Nginx配置

Nginx作为反向代理的关键配置如下:

server {
    listen 443 ssl http2;
    server_name mercure.yourdomain.com;
    
    ssl_certificate /path/to/cert.pem;
    ssl_certificate_key /path/to/key.pem;
    
    location / {
        # CORS相关配置
        if ($http_origin ~ '^https?://(localhost(:[0-9]+)?|127.0.0.1(:[0-9]+)?|[^/]*\.yourdomain\.com)') {
            set $cors "true";
        }
        
        if ($cors = "true") {
            add_header 'Access-Control-Allow-Origin' '$http_origin' always;
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Allow-Headers' 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range';
            add_header 'Access-Control-Allow-Methods' 'GET,POST,OPTIONS';
            add_header 'Content-Type' 'text/event-stream';
        }
        
        # 反向代理配置
        proxy_pass http://localhost:3000;
        proxy_read_timeout 24h;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
        proxy_connect_timeout 300s;
        proxy_buffering off;  # 重要:禁用缓冲以确保SSE正常工作
        
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Mercure服务配置

Caddyfile配置

Mercure使用Caddy作为其底层服务器,以下是推荐的Caddyfile配置:

{
    http_port 3000
    auto_https off
}

http://localhost {
    log {
        output file /var/log/caddy/mercure.log {
            roll_size_mb 10
            roll_keep 5
        }
        level INFO
    }

    encode zstd gzip

    mercure {
        transport_url bolt://mercure.db
        publisher_jwt {env.MERCURE_PUBLISHER_JWT_KEY} {env.MERCURE_PUBLISHER_JWT_ALG}
        subscriber_jwt {env.MERCURE_SUBSCRIBER_JWT_KEY} {env.MERCURE_SUBSCRIBER_JWT_ALG}
        cors_origins https://yourdomain.com https://localhost:8080
        publish_origins *
        anonymous
        subscriptions
    }

    respond /healthz 200
}

系统服务配置

为了让Mercure作为系统服务运行,创建以下systemd服务文件:

[Unit]
Description=Mercure Service
After=network.target

[Service]
Type=simple
EnvironmentFile=/etc/environment
ExecStart=/usr/bin/mercure run --config /path/to/Caddyfile
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target

应用集成

后端集成(以Symfony为例)

在Symfony应用中配置Mercure:

# config/packages/mercure.yaml
mercure:
    hubs:
        default:
            url: '%env(MERCURE_URL)%'
            public_url: '%env(MERCURE_PUBLIC_URL)%'
            jwt: 
                value: '%env(MERCURE_JWT_SECRET)%'
                publish: '*'

前端集成(以Vue.js为例)

在前端应用中订阅Mercure事件:

const hubUrl = new URL('https://mercure.yourdomain.com/.well-known/mercure');
hubUrl.searchParams.append('topic', 'https://api.yourdomain.com/notifications/all');

const eventSource = new EventSource(hubUrl, { withCredentials: true });
eventSource.onmessage = event => {
    console.log('Received update:', event.data);
};

常见问题解决

  1. CORS问题:确保Nginx配置中正确设置了CORS头信息,特别是Access-Control-Allow-OriginAccess-Control-Allow-Credentials

  2. 连接断开问题:在Nginx配置中添加proxy_buffering off;可以防止SSE连接被意外缓冲导致的问题。

  3. JWT验证失败:确保发布者和订阅者的JWT密钥配置一致,且算法设置正确。

  4. 性能优化:适当调整proxy_read_timeoutproxy_connect_timeout值以适应您的应用场景。

总结

通过以上配置,我们成功地在Nginx反向代理后部署了Mercure服务,并实现了前后端的集成。关键点在于:

  • 正确配置Nginx的反向代理和CORS设置
  • 合理设置Mercure的Caddyfile
  • 确保系统服务配置正确
  • 前后端集成时注意URL和凭证的配置

这些配置不仅解决了基本的通信问题,还考虑了生产环境中的安全性、可靠性和性能要求。

登录后查看全文
热门项目推荐

项目优选

收起
ohos_react_nativeohos_react_native
React Native鸿蒙化仓库
C++
176
261
RuoYi-Vue3RuoYi-Vue3
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
860
511
ShopXO开源商城ShopXO开源商城
🔥🔥🔥ShopXO企业级免费开源商城系统,可视化DIY拖拽装修、包含PC、H5、多端小程序(微信+支付宝+百度+头条&抖音+QQ+快手)、APP、多仓库、多商户、多门店、IM客服、进销存,遵循MIT开源协议发布、基于ThinkPHP8框架研发
JavaScript
93
15
openGauss-serveropenGauss-server
openGauss kernel ~ openGauss is an open source relational database management system
C++
129
182
openHiTLSopenHiTLS
旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
259
300
kernelkernel
deepin linux kernel
C
22
5
cherry-studiocherry-studio
🍒 Cherry Studio 是一款支持多个 LLM 提供商的桌面客户端
TypeScript
596
57
CangjieCommunityCangjieCommunity
为仓颉编程语言开发者打造活跃、开放、高质量的社区环境
Markdown
1.07 K
0
HarmonyOS-ExamplesHarmonyOS-Examples
本仓将收集和展示仓颉鸿蒙应用示例代码,欢迎大家投稿,在仓颉鸿蒙社区展现你的妙趣设计!
Cangjie
398
371
Cangjie-ExamplesCangjie-Examples
本仓将收集和展示高质量的仓颉示例代码,欢迎大家投稿,让全世界看到您的妙趣设计,也让更多人通过您的编码理解和喜爱仓颉语言。
Cangjie
332
1.08 K