Nginx – How to Rewrite URLs Without Redirection

nginxrewrite

I used rewrite directives below in nginx to rewrite urls of static files to external CDN server.

rewrite ^/static/(css|images|js)/([a-z_\-\.]+)$ http://cdn.domain.com/$1_$2 last;

It works but it redirect the url automatically in browsers.

How can I do the above rewrite without redirects?

Best Answer

You need to change the links inside your application to point to the CDN for static includes.

When you rewrite to an http location there's nothing nginx can do but redirect the browser (since the CDN is outside of nginx, and the browser needs to get the files from the CDN). You would have the same issue with Apache or any other URL rewriter, as the CDN is not an "internal" location to the web server.

One option might be the nginx subsitution module, which can replace content as it is delivered. But that doesn't handle regular expressions, and would slow down every request. It is better just to change your application's HTML to reference the CDN URLs directly.