25

all...

I am trying to do something in nginx to redirect all calls for files in

/images/

to become in:

/assets/images/

can someone help me with the rewrite rule? giving a 301 moved permanently status?

alybadawy
  • 489
  • 2
  • 7
  • 13

2 Answers2

53

Here's the preferred way to do this with newer versions of Nginx:

location ~ ^/images/(.*) {
    return 301 /assets/images/$1;
}

See https://www.nginx.com/blog/creating-nginx-rewrite-rules/ for more info.

gsf
  • 1,778
  • 16
  • 11
  • 1
    What is `~` for? And the `^` ? Would it work with `$request_uri` instead of `$1` ? – pyfork Dec 25 '16 at 02:43
  • 4
    @ingo See the [location documentation](http://nginx.org/en/docs/http/ngx_http_core_module.html#location). The `~` (tilde) says this is a case-sensitive regex. Otherwise, URLs for `/Images` and `/imAgEs` would match. If this is the desired behavior then make it case-insensitive with `~*`. – gsf Dec 26 '16 at 14:33
  • 4
    @ingo The `^` (caret) at the front of the regex anchors it to the beginning of the line. Without it, URLs like `/some/plugin/images/blah.jpg` would also match. – gsf Dec 26 '16 at 14:34
  • 3
    @ingo In this case, `location /images/ {return 301 /assets$request_uri;}` would work. If the redirect does anything other than prepend to the original directory, however (e.g. `/images` -> `/pics`), the regex and `$1` are still necessary. – gsf Dec 26 '16 at 14:47
  • 1
    You are a true lifesaver @gsf – Jordan Lagan Jun 17 '21 at 16:04
7

Add below configuration into your nginx.conf

rewrite ^/(images.*) /assets/$1 permanent;
oldmonk
  • 739
  • 4
  • 10
  • 4
    `return 301` instead of rewriting is preferred ( https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/#taxing-rewrites ), see the answer by @gsf – MeXx Feb 15 '16 at 18:15