Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Replacing Text in NGINX with sub_filter

DZone's Guide to

Replacing Text in NGINX with sub_filter

Weird situations arise sometimes with web applications. Come have a look at how you might overcome these situations when you need to replace text like IP addresses or files with NGINX!

· Performance Zone
Free Resource

Discover 50 of the latest mobile performance statistics with the Ultimate Guide to Digital Experience Monitoring, brought to you in partnership with Catchpoint.

Sometimes you find yourself in a weird predicament. A third party application that you’ve slapped NGINX in front of insists on using internal IP addresses or ports despite your reverse proxy passing all the correct headers and other pieces required. Or maybe you’ve found yourself in the situation I found myself in last week where you have a third party internal application wanting to reference a file on a CDN. As luck would have it, that CDN has been deprecated and changing it requires rebuilding a jar where the script path is hardcoded and then repackaging the internal application that uses it. Long story short, we’ll soon be doing some yak shaving that could possibly take all day so how about we just use sub_filter instead and take a nap?

Use It

Thankfully most stock builds of NGINX include ngx_http_sub_module by default. Using it is actually simple enough, just slap the following directive under your location or server directive in nginx.conf.

And that’s it! You can also use regular expression here as well. sub_filter_once indicates whether NGINX should apply the replacement once or repeatedly. One gotcha you might have is that by default this only works with mime types of text/html. If you want to modify the mime-types that subfilter executes on set `sub_filter_types` to the desired type.

Give It a Try

I’ve put together a very simple demonstration of using subfilter for text replacement on Github.

Is your APM strategy broken? This ebook explores the latest in Gartner research to help you learn how to close the end-user experience gap in APM, brought to you in partnership with Catchpoint.

Topics:
nginx ,filter ,tip ,trick ,code

Published at DZone with permission of James Carr, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}