Wednesday, August 2, 2017

Nginx rewrite URLs but not static 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.


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/(?.+)$ {

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/(?.+)$ {
rewrite ^ http://www.domain.com/wp-content/$filename permanent;

}

No comments:

Post a Comment

linux - How to SSH to ec2 instance in VPC private subnet via NAT server

I have created a VPC in aws with a public subnet and a private subnet. The private subnet does not have direct access to external network. S...