My final solution to get CDN working.
On main host you have to rewrite some URLs in HTML. For Apache2 it will looks as following:
Note: HOST is original Nextcloud URL and cdn.HOST is CDN.
<Location "/">
# We will only edit HTML, no
AddOutputFilterByType INFLATE;SUBSTITUTE text/html
# We will put size 2 Mb to aviod 500 Error by KeeWeb App crash
SubstituteMaxLineLength 2M
# Replace relative URL to the Absolute
Substitute "s|\"/index.php/apps/|\"https://cdn.HOST/index.php/apps/|inq"
Substitute "s|\"/core/|\"https://cdn.HOST/core/|inq"
Substitute "s|\"/dist/|\"https://cdn.HOST/dist/|inq"
Substitute "s|\"/apps/|\"https://cdn.HOST/apps/|in"
### Workaround for Memories ###
# We will put back memories scripts to load from original URL, not CDN
Substitute "s|https://cdn.HOST/apps/memories|/apps/memories|in"
### End Workaround for Memories ###
# We will edit CSP Header to enable fonts, img, scripts and styles to be loaded from CDN:
# - font, img, script, style needs for a static content
# - frame needs for a keepass to be able to open DB from the cloud
# - connect needs for UI upload
Header always edit* Content-Security-Policy (font|img|script|style|frame|connect)-src "$1-src https://cdn.HOST"
# OPTIONAL
# Some SVGs are part of CSS and JS, that are hard to edit, so lets
# Redirect SVG files to the CDN
# For this you HAVE to add CDN host to the trusted domains
RedirectMatch "^/apps/(.*)\.svg$" "https://cdn.HOST/$0"
</Location>
On CDN side I have following addons to the default Nextcloud configuration:
# We will only enable folders for CDN, the rest will be not accessible
<Location ~ "^((?!/apps|index.php/apps/theming|dist|core).)*$">
## We can ether redirect to original Cloud URL, or drop 404 to the files should not be accessible via CDN. Please select only one.
## Redirect to the cloud URL
#Redirect permanent https://cloud.HOST/
## Show 404
RewriteEngine On
RewriteRule ^ - [R=404]
</Location>
# We will set CORS to enable loading from the ORIGINAL DOMAIN via CDN
Header always set Access-Control-Allow-Origin 'https://cloud.HOST'
Header always set Vary 'Origin'
# We will add workaround for keeweb, it tries to call CDN instead of CLOUD
Redirect 301 "/index.php/login" "https://cloud.HOST/index.php/login"
Basically thats all… If somebody calls my CDN directly or not apps from nextcloud, he will see 404, for the rest works pretty good. Just check how data flows via CDN:
