Nginx rewrite URLs but not static files

nginxrewritestatic-files

I need to rewrite URLs like

http://www.domain.com/blog/wp-content/uploads/this-is-a-static-file.jpg

to

http://www.domain.com/wp-content/uploads/this-is-a-static-file.jpg

I am using this rule:

location /blog/wp-content$ {
        rewrite ^/blog/wp-content/(.*)$ /wp-content$1 last;
}

The weird thing is that only URLs directly behind wp-content and without static files are rewritten correctly:

http://www.domain.com/blog/wp-content/uploads/ => http://www.migayopruebas.com/wp-content/uploads/

However, it there are more than one sub level OR a static file is involved, it doesn't work:

http://www.domain.com/blog/wp-content/uploads/migayo-trangulacion-laton.jpg => doesn't change

http://www.domain.com/blog/wp-content/migayo-trangulacion-laton.jpg => doesn't change

Could anyone point me out to the right way to do this? I've been read Nginx doc and several examples and still can't make it work.

Thanks a lot, regards.

Best Answer

Your solution doesn't work, because you don't have a regex location (the ~ character is missing), and you end the location with the $, which is a regex character.

You can do it in a bit simpler way:

location ~ /blog/wp-content/(?<filename>.+)$ {
    rewrite ^ /wp-content/$filename last;
}

So, here you do the regex capture in the location directive, and use the captured part of the path with the rewrite destination.

If you want to make a client side 301 redirect, use the following:

location ~ /blog/wp-content/(?<filename>.+)$ {
    rewrite ^ http://www.domain.com/wp-content/$filename permanent;
}