brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: nginx sub_filter rewrites text in a proxied page on the fly

Nginx
~/tips/tip-nginx-sub-filter-rewrite-html

sub_filter 'http://127.0.0.1:8081/' 'https://example.com/app/';

Replaces strings in HTML from a backend, like hardcoded internal URLs, before it reaches the browser.

Some apps write their internal address into every link, so a page served through the proxy still points to http://127.0.0.1:8081/. When the app has no setting for its public URL, nginx can replace the text.

location /app/ {
    proxy_pass http://127.0.0.1:8081/;
    proxy_set_header Accept-Encoding "";
    sub_filter 'http://127.0.0.1:8081/' 'https://example.com/app/';
    sub_filter_once off;
}

Each sub_filter line is a search and replace on the response body. sub_filter_once off replaces every match instead of only the first one, which is what you want for links. You can also inject things: replacing </head> with a stylesheet link plus </head> adds your own CSS to a page you cannot edit. Both work together in one location, and the page comes out with the new links and the extra stylesheet.

The Accept-Encoding "" line matters. If the backend sends gzip, nginx sees compressed bytes and replaces nothing. Clearing the header makes the backend send plain text; nginx can still compress the result for the browser.

By default only text/html is filtered. JSON or JavaScript with the same URLs needs sub_filter_types, and that costs CPU on large responses. The matching is plain text, so a URL the app builds in JavaScript from pieces slips through. I see this as a patch for apps that leave you no choice; a base URL setting in the app is always the better fix.

Further reading: ngx_http_sub_module

Going deeper: Guide: fix a 502 Bad Gateway in Nginx Proxy Manager, with a checklist that finds the cause

More Nginx tips sudo certbot --nginx -d example.com -d www.example.com /data/nginx/custom/server_redirect.conf map $http_upgrade $connection_upgrade { proxy_intercept_errors on; proxy_redirect http://localhost:3000/ /app/; All Nginx tips (50) All topics

Link