1

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.

arg
  • 13
  • 1
  • 4

2 Answers2

2

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;
}
Tero Kilkanen
  • 36,796
  • 3
  • 41
  • 63
  • I would include the slash after wp-content in the location so it doesn't match unexpectedly. –  Jun 24 '14 at 07:01
  • It works, thank you very much :) I am surprised to see that despite the links work, the URL in the browser bar doesn't change. Do you know if I can force the change in the URL? Regards and thanks again. – arg Jun 24 '14 at 18:29
  • Edited answer to provide client side redirect which changes browser URL. – Tero Kilkanen Jun 24 '14 at 18:33
  • Work like a charm. Your answer goes straight to Evernote. Thanks again. – arg Jun 24 '14 at 18:58
1

(I post an answer because >50 reputation is needed to comment)

Why the "$" ?

You probably want this:

location /blog/wp-content/ {
        rewrite ^/blog/wp-content/(.*)$ /wp-content$1 last;
}
moebius_eye
  • 1,103
  • 7
  • 21