Nginx: Redirect a certain file path url to its new path url

18,399

A Simple rewrite will do, add this to your server block.

rewrite ^(/documents/.*)$ /assets/client_files/files$1 permanent;

This will throw a 301 redirect ot requests with URI staring with /documents/ to the new path.

For more information about Nginx rewrite, check the docs here

UPDATE

Also you can do this inside a location like this

location /documents/ {
    rewrite ^(.*)$ /assets/client_files/files$1 permanent;
}
Share:
18,399
Tinker
Author by

Tinker

Updated on June 27, 2022

Comments

  • Tinker
    Tinker almost 2 years

    We moved the assets to a new container or folder. From /documents/THE_FILE.pdf was moved to /assets/client_files/files/documents/THE_FILE.pdf noticed the path is now within /assets/cleint_files/files/ directory.

    The problem is, we already have bunch of content that have links to file but using the old path. I just want to make the work simple, since there are like 2,000 instances of these throughout the site. I'm hopeful this could be done using nginx that it will redirect a certain url to its new url when it detected a link like this http://www.domain.com/documents/THE_FILE.pdf. As long as the url's first path is /documents/, it will be redirected to new path /assets/client_files/files/documents/

    Thank you.

  • Tinker
    Tinker almost 8 years
    sorry but i can't use server block, instead just location block. Is there a way to do that using location block?
  • Zac Grierson
    Zac Grierson almost 7 years
    Wouldnt you want to use return 301 to support seo and robots?
  • Lution
    Lution almost 7 years
    @ZacGrierson A rewrite command with option permanent does the same work with return 301.
  • qräbnö
    qräbnö almost 6 years
    rewrite ... permanent or return 301 ... is sucky if you want to test something, because the browser remembers this. Use rewrite ... redirect or return 302 ... instead!