404 rewrite or redirect nginx path

user2925795 asked:

Im having problems with redirect on nginx

I have this original URL:

https://www.example.com/media/wysiwyg/logo.png

And i’m using the Cloudflare Image, i can use this to load by Cloudflare Image:

https://www.example.com/cdn-cgi/image/onerror=redirect/media/wysiwyg/logo3.png 

But i need this dynamic, like:

Everything in this folder: “media/wysiwyg/” will redirected to:

https://www.example.com/cdn-cgi/image/format=auto,onerror=redirect/media/wysiwyg/logo.png

logo.png would be dynamic, BUT MUST BE AN IMAGE (JPEG, GIF, PNG).

I tried this, but without success:

location ~ ^/media/wysiwyg/(.*)$ {
    rewrite    ^/media/wysiwyg/(.*)$ /cdn-cgi/image/format=auto,onerror=redirect/media/wysiwyg/$1 break;
}

I need, if i access this:

https://www.example.com/media/wysiwyg/logo.png

I need redirect to this (without change url):

https://www.example.com/cdn-cgi/image/format=auto,onerror=redirect/media/wysiwyg/logo.png

What’s wrong?

My answer:


Change break to last.

Because the new URL will need to be processed by a different location, you need to have nginx restart processing for the new rewritten URL, which is only done when you use last in the rewrite rule.

See the docs for the complete explanation of how rewrite works.


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.