进阶 docs.nodebb.org 2026-10-13 15:07:09 · 36 阅读
第22章 Apache(v2.4+)配置代理指南
将 Apache 配置为代理
NodeBB 默认运行在 4567 端口,这意味着通常需要通过主机名加端口号的方式访问构建实例(例如 http://example.com:4567)。
若希望在不指定端口的情况下托管 NodeBB,可以将 Apache 设置为代理:将所有指向特定主机名(或子域名)的请求转发至运行在任意端口的上游 NodeBB 实例。
前提条件
注意
此配置需要 Apache v2.4.x 或更高版本。如果你使用的是较旧的 Apache v2.2.x,请参阅 Apache v2.2.x 说明。
你需要启用以下 Apache 模块:
sudo a2enmod proxy
sudo a2enmod proxy_http
sudo a2enmod proxy_wstunnel
sudo a2enmod rewrite
sudo a2enmod headers
配置
下一步是创建配置文件,通常以站点名称命名(例如 www.example.com.conf),存放在 Apache vhost 配置目录中,一般位于 /etc/apache2/sites-available/。请确保 ServerName 与 config.json 中定义的 URL 字段匹配。
以下是在 4567 端口运行 NodeBB 的最小化 Apache 虚拟主机配置。
ServerName www.example.com
RequestHeader set X-Forwarded-Proto "http"
ProxyRequests off
Order deny,allow
Allow from all
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/socket.io [NC]
RewriteCond %{QUERY_STRING} transport=websocket [NC]
RewriteRule /(.*) ws://127.0.0.1:4567/$1 [P,L]
ProxyPass / http://127.0.0.1:4567/
ProxyPassReverse / http://127.0.0.1:4567/
下面是一个更高级的 Apache 虚拟主机配置,使用了 TLS、HTTP/2 和静态文件缓存头,并将 http 流量永久重定向到 HTTPS!
ServerName www.example.com
ServerAlias example.com
# 将所有 http 流量重定向到主要的 https 站点
RewriteEngine On
RewriteRule ^[^\/]*\/(.*) https://www.example.com/$1 [R=301,L]
Protocols h2 http/1.1
ServerName www.example.com
SSLEngine on
SSLCertificateFile /path/to/cert.pem
SSLCertificateKeyFile /path/to/privkey.pem
SSLCertificateChainFile /path/to/chain.pem
# 基本安全头
Header always set X-Content-Type-Options "nosniff"
Header always set X-Xss-Protection "1; mode=block"
# NodeBB 请求头
RequestHeader set X-Forwarded-Proto "https"
# 静态文件缓存
ExpiresActive on
ExpiresDefault "access plus 14 days"
Header set Cache-Control "public"
ProxyRequests off
Order deny,allow
Allow from all
# 当 NodeBB 离线时的自定义错误页面
ProxyPass /error-documents !
ErrorDocument 503 /error-documents/503.html
Alias /error-documents /path/to/nodebb/public
# WebSocket 透传
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/socket.io [NC]
RewriteCond %{QUERY_STRING} transport=websocket [NC]
RewriteRule /(.*) ws://localhost:4567/$1 [P,L]
ProxyPass / http://localhost:4567/
ProxyPassReverse / http://localhost:4567/
# 日志记录
ErrorLog ${APACHE_LOG_DIR}/www-example-error.log
CustomLog ${APACHE_LOG_DIR}/www-example-access.log combined
配置 Apache 使用自定义错误页面
本示例演示如何配置 Apache,当你的论坛未运行时显示自定义的 503 错误页面。
创建你的自定义错误页面
你可以创建自己的 503.html,也可以使用 NodeBB 安装时自带的版本。若要自行创建,请新建一个 503.html 文件,并将其放置在 NodeBB 公开目录下的子文件夹 /path/to/nodebb/public/error-documents 中。
如果你想使用 NodeBB 自带的版本,请将 public 目录下的 503.html 复制到上述提到的子文件夹中。
请确保在 503_custom.html 文件中添加内容。以下是一个示例,你可以直接复制粘贴:
在此插入你的页面标题
在此插入你的内容。
配置 Apache 使用自定义错误页面 接下来需要告诉 Apache,当发生对应错误时调用我们自定义的页面。打开虚拟主机配置文件 /etc/apache2/sites-available/www.example.com.conf。 将以下内容添加到活动虚拟主机部分,并相应修改路径。 ProxyPass /error-documents ! ErrorDocument 503 /error-documents/503.html Alias /error-documents /var/www/nodebb/nodebb/public/error-documents 使用 Alias 指令是为了更方便地将其排除在 ProxyPass 指令之外。 重新加载 Apache(sudo service apache2 reload),下次当论坛未运行时访问,用户将看到你的自定义页面。