Использование Discourse с Cloudflare: лучшие практики

Использование Discourse с Cloudflare

:bookmark: В этом руководстве объясняется, как настроить и использовать Discourse с Cloudflare, включая лучшие практики безопасности и советы по устранению неполадок.

:person_raising_hand: Требуемый уровень пользователя: Администратор

:information_source: Для самостоятельной установки требуется доступ к консоли

Краткое содержание

Cloudflare может улучшить ваш экземпляр Discourse, обеспечив повышенную производительность благодаря CDN, дополнительные уровни защиты, такие как защита от DDoS-атак, и поддержку HTTPS. Это руководство охватывает процесс настройки и лучшие практики для оптимальной конфигурации.

Зачем использовать Cloudflare с Discourse

Использование Cloudflare с вашим экземпляром Discourse дает несколько ключевых преимуществ:

  • Производительность: CDN Cloudflare может улучшить глобальный доступ к общим ресурсам, улучшая пользовательский опыт по всему миру (источник)
  • Безопасность: Дополнительные уровни защиты, включая:

:warning: Для самостоятельных установок, хотя Cloudflare предлагает эти преимущества, он добавляет сложности в вашу настройку.

Настройка Cloudflare

  1. Ознакомьтесь с основами Cloudflare
  2. Следуйте инструкциям по настройке, чтобы настроить Cloudflare для вашего домена и получить преимущества в области безопасности, производительности и надежности

Лучшие практики конфигурации

Настройки DNS

  • Убедитесь, что записи DNS, указывающие на ваш экземпляр Discourse, проксируются
  • Доступ к настройкам DNS осуществляется по адресу dash.cloudflare.com/?to=/:account/:zone/dns

Конфигурация SSL/TLS

  • Установите режим шифрования в значение “Full (strict)”
  • Доступ к настройкам SSL/TLS осуществляется по адресу dash.cloudflare.com/?to=/:account/:zone/ssl-tls

:warning: Неправильная конфигурация SSL/TLS может вызвать циклы перенаправления

Настройки кэширования

  • Установите уровень кэширования в значение “Standard”
  • Доступ к настройкам кэширования осуществляется по адресу dash.cloudflare.com/?to=/:account/:zone/caching/configuration

Правила кэширования

Cloudflare устарел Page Rules в пользу своей современной системы Rules. Создайте следующие правила, используя Cache Rules по адресу dash.cloudflare.com/?to=/:account/:zone/rules:

  • Установите уровень кэширования в значение “Bypass” для community.example.com/session/*
  • Настройте параметры нормализации URL для нормализации входящих URL-адресов

Настройки сети

Настройки сети по адресу dash.cloudflare.com/?to=/:account/:zone/network обычно не влияют на функциональность Discourse. Discourse не использует WebSockets, gRPC или заголовки CF-IPCountry / True-Client-IP. Эти настройки можно оставить по умолчанию, если другое программное обеспечение на том же домене не требует специальной конфигурации.

Настройки WAF (брандмауэр веб-приложений)

Если ваш тарифный план Cloudflare поддерживает управляемые правила, создайте следующие:

  1. Пропустить WAF при создании/редактировании постов:
(starts_with(http.request.uri.path, "/posts") and http.request.method in {"POST" "PUT"})
  1. Для пользователей плагина Data Explorer пропустите WAF при административных запросах:
((http.request.uri.path contains "/admin/plugins/explorer/queries/" or http.request.uri.path contains "/admin/plugins/discourse-data-explorer/queries/") and http.request.method eq "PUT")

Для обоих правил:

  • Выберите “Skip all remaining rules”
  • Включите “Log matching requests”

:information_source: Если у вас тарифный план Business или выше, вы можете использовать оператор регулярных выражений matches для более точного сопоставления. Операторы starts_with и contains, использованные выше, работают во всех тарифных планах, включая Free и Pro.

Доступ к настройкам WAF осуществляется по адресу dash.cloudflare.com/?to=/:account/:zone/firewall/managed-rules

Оптимизация контента

Настройте следующее по адресу dash.cloudflare.com/?to=/:account/:zone/speed/optimization:

  • Включите Brotli
  • Отключите Rocket Loader™

:warning: Discourse часто получает отчеты о неработоспособности сайта из-за включенного Rocket Loader™

Дополнительная конфигурация для самостоятельных установок

Чтобы обеспечить правильную пересылку IP-адресов, добавьте следующее в раздел шаблонов в вашем файле containers/app.yml:

- "templates/cloudflare.template.yml"

:warning: После добавления шаблона необходимо пересобрать контейнер с помощью команды ./launcher rebuild app, чтобы изменения вступили в силу.

Связанное: Как настроить Cloudflare?

Ресурсы поддержки

Устранение неполадок

Проблемы с политикой безопасности контента (CSP)

Если вы столкнулись с ошибками CSP:

  • Убедитесь, что Rocket Loader отключен
  • Проверьте, что скрипты правильно добавлены в настройку сайта content security policy script src

Функциональность OneBox

Если OneBox блокируется:

  • Проверьте, включен ли режим борьбы с ботами Super Bot Fight Mode
  • Отрегулируйте настройку “Definitely automated”, если она установлена в “Managed” или “Block”
  • Рассмотрите возможность создания пользовательского правила WAF для пользовательского агента OneBox
29 лайков

Good morning,

Thank you for this guide which I followed to the letter but I encounter a problem, each time I activate Cloudflare in my console I get an error with the CSP which displays to me (Refused to execute inline script because it violates the following Content Security Policy directive: "script-src) and after having indicated to me the urls present in my CSP: (Either the ‘unsafe-inline’ keyword, a hash (‘sha256-VCiGKEA…=’), or a nonce (‘nonce-…’) is required to enable inline execution.

I tried looking everywhere but I can’t find a solution other than disabling the proxy which solves my problem?

THANKS.

Can you check if rocket loader is turned off?

Another thing is to check that the scripts are appropriately added to content security policy script src site setting.

If none of these are working out, I suggest reaching out to Cloudflare @ https://community.cloudflare.com/t/using-discourse-with-cloudflare-best-practices/602890.

1 лайк

Thanks for this @nat and @tcloonan

This has been on my list of things to do for a year or two, but I’ve been put off by the age of some of the older threads on this subject :smiley:

Any issues or special things for people using AWS S3 for storage and for backups? :thinking:

Do you still need the cloudflare template in app.yml for true IP addresses or has that changed over the years?

1 лайк

Yes. You do need the cloudflare template. Without it, all traffic will appear to come from cloudflare’s servers rather than the user’s browser IP.

I don’t see it mentioned in the OP, which seems like a glaring omission. How did you infer that you needed it?

2 лайка

Hi! Been around since 2014 (some years mostly silent) but have been working our getting our community migrated over since 2020 with a custom importer, and we are working on the second version of our in-house plugin to insert and enable bbob as a bbcode engine into Discourse. You can follow our progress here: GitHub - RpNation/bbcode: RpNation's Official BBCode Implementation for Discourse

I’ve been breathing this software for a bit now. We do use Cloudflare, so I’ve been re-researching what if any issues it has with discourse, since we are now at the stage where I can start worrying about less vital things that are not considered blockers.

@nat Could you add an edit about the template for self-hosted instances!

4 лайка

Done, thank you both for pointing this out!

4 лайка

Thank you very much! That was probably also the reason why my site was suddenly no longer accessible. I must have played with the Cloudflare settings a bit too much.

Since my old domain provider only supported DNSSec inadequately & incorrectly, I had to look for something new. That’s when Cloudflare came to mind. The free plan is completely sufficient for me. It’s a shame that the tariffs don’t even scale reasonably to the requirements.

2 лайка

Is it adding to this location?
image

1 лайк

Just for accuracy, the query for the WAF exclusion is:

(http.request.uri.path eq "/posts(/[0-9]+)?" and http.request.method in {"POST" "PUT"})

You can copy-paste it if you click on the Edit expression on the left instead of using the form selection.

Noticed today as I updated and suddenly half the forum wasn’t working due to Auto Minify :weary:

Edit: just noticed this is a wiki post. Silly me, I have edited the initial post.

4 лайка

SSL/TLS encryption mode Full (strict). Will there be a problem if it is not closed? Won’t automatic SSL be defined anyway?

Just to add to this, seems the OneBox functionality is being blocked when Super Bot Fight Mode is on and the setting Definitely automated is set to Managed or block…

You can get around this by setting up a custom WAF rule for the Onebox user agent but perhaps there is a more secure way of doing this?

Related to

this part might need some better wording:

@supermathie Suggestion:

you will want to add the following line to the end of your templates section in containers/app.yml.

as illustrated in Using Discourse with Cloudflare: Best Practices - #11 by shawa

At best, a link to a general how-to about templates in server configuration could be provided also, which I was not able to find at first sight.

I would suggest turning off AI bots within Cloudflare. This can be found under security->bots->block AI bots.

The AI bots were hammering my site with 30K to 40K page views daily. After turning on this filter, my AI bot traffic significantly dropped.

5 лайков

The above code should be changed to:

 - "templates/cloudflare.template.yml"

thanks,
Major

2 лайка

Is it really true that WebSockets support should be enabled in Cloudflare?

Worked well for us without for years, and as far as I could find info here on the forum, Discourse does not make any use of WebSockets.

i dont understand if i have to do this

You are right. I don’t believe we use Websockets.

I’ve removed it, and also updated the template snippet from the user above.

2 лайка

While on it, I think the whole Network settings are irrelevant for Discourse:

  • IPv6 compatibility cannot be disabled anymore, and of course Discourse does not depend on it, but can perfectly run on an IPv4-only system.
  • IP Geolocation adds the CF-IPCountry header to requests, which is however not used by Discourse. It uses its own (optional) MaxMind feature.
  • Network Error Logging adds the Report-To response header, which browsers can use to report errors to. It is however deprecated, and even that the feature can be enabled with all Cloudflare plans, the dashboard element to actually view the reports is available only with Enterprise plan. So in this case for some old browsers it might just be a privacy regression and network overhead.
  • Onion Routing enhances privacy for requests coming from the Tor network. Discourse won’t care or even know this.
  • The Pseudo IPv4 feature might even be needed if the host runs some software, like ancient analytics or similar, which supports IPv4 addresses only. The proxy headers of Cloudflare, like Cf-Connecting-IP (or others, depending on what one configures) can then be adjusted to have a moreless unique IPv4 address, instead of the actual IPv6 address of the client, to work around the fact that IPv6 support for client->Cloudflare requests cannot be disabled anymore. Again, Discourse won’t care. I mean it would be a problem for e.g. GeoIP detection, but the feature is disabled by default, and admins of course should enable it only, if strictly required by whichever software they run, accepting the downside of non-true client IPs. It can be also configured to only add a new header with the pseudo IPv4 address, and analytics (or whatever) requests can then rewrite client IP headers where needed, while requests to Discourse would not be affected. In any case, for Discourse functionality in general, the feature is irrelevant.
  • True-Client-IP Header adds just this header in addition to CF-Connecting-IP and X-Forwarded-For. Discourse does not make use of it, also the Discourse config template uses CF-Connecting-IP instead. So it has no effect.
  • gRPC is not used by Discourse, but having Cloudflare enabled to forward gRPC requests does not hurt either, same as with WebSockets. Both might be needed enabled for other software running on the same Cloudflare domain.
  • Maximum Upload Size 100 MB is default and minimum. Larger upload sizes require Business or Enterprise plans, and Discourse won’t break if Cloudflare allows larger uploads.

The only thing I am not sure about whether it can have an effect is Response Buffering. And I cannot test as it is an Enterprise-only feature. But I cannot imagine that the client cares whether packets are streamed form CF edge as they come in, or sent in one chunk ones compete at the edge. For cached data (cached at Cloudflare I mean), this is done always anyway, and there is does not cause issues, at least. This feature only affects non-cached data.

So basically I would remove the whole “Network settings” section as something which is irrelevant for Cloudflare functionality, but other software might require certain settings or admins might prefer them a certain way, and should know that Discourse will function in any case.

1 лайк