Nginx – Using nginx to rewrite urls inside outgoing responses

haproxynginxrewrite

We have a customer with a site running on Apache. Recently the site has been seeing increased load and as a stop gap we want to shift all the static content on the site to a cookieless domains, e.g. http://static.thedomain.com.

The application is not well understood. So to give the developers time to amend the code to point their links to the static content server (http://static.thedomain.com) I thought about proxying the site through nginx and rewriting the outgoing responses such that links to /images/... are rewritten as http://static.thedomain.com/images/....

So for example, in the response from Apache to nginx there is a blob of Headers + HTML. In the HTML returned from Apache we have <img> tags that look like:

<img src="/images/someimage.png" />

I want to transform this to:

<img src="http://static.thedomain.com/images/someimage.png" />

So that the browser upon receiving the HTML page then requests the images directly from the static content server.

Is this possible with nginx (or HAProxy)?

I have had a cursory glance through the docs but nothing jumped out at me except rewriting inbound urls.

Best Answer

There is a http://wiki.nginx.org/HttpSubModule - "This module can search and replace text in the nginx response."

copy past from docs:

Syntax:

sub_filter string replacement

Example:

location / {
  sub_filter      </head>
  '</head><script language="javascript" src="$script"></script>';
  sub_filter_once on;
}