Skip to main content
This lesson shows how to use the Nginx rewrite directive to transparently map legacy URLs to new paths so existing bookmarks and external links keep working. The example scenario: a site previously served images from /images/ but has been reorganized to serve them from /pics/. We want requests for /images/... to continue working by rewriting them to /pics/... on the server. Example requests to preserve:
How the rewrite works
  • Using rewrite ^/images/(.*)$ /pics/$1; tells Nginx to internally map any request starting with /images/ to the equivalent path under /pics/.
  • If you add the permanent flag (e.g. rewrite ^/images/(.*)$ /pics/$1 permanent;) Nginx will return an HTTP 301 redirect to the client. Without the flag the rewrite is internal: the browser URL remains /images/... but the server serves the file from /pics/....
Quick rule example:
Using permanent (301) will update client caches and search engine indexes. Only use permanent when you are sure the change is permanent. For temporary behavior, omit the flag to keep rewrites internal.
Open the site on port 80 and verify an image URL works. For example:
A screenshot of a minimalist webpage template titled "Phantom" with a large headline and a short paragraph of placeholder text. Below the header is a grid of colorful square feature cards labeled with words like "MAGNA", "LOREM", and "FEUGIAT".
Verify site content on disk
  • If the site root is /var/www/html, list the directory and confirm the images/ folder exists:
Preserve original content while moving
  • To keep the original images/ directory in place while making the content available under pics/, copy it:
Confirm files inside images/:
Add the rewrite to your site configuration
  • Edit your site file (for example /etc/nginx/sites-available/example) and place the rewrite directive inside the location / block so requests for /images/... are mapped to /pics/.... A minimal example:
Test configuration and reload Nginx
Verify in the browser
  • Open the site in a fresh browser session or an incognito/private window and request an old /images/... URL. For example:
  • With the permanent flag the browser will be redirected to http://.../pics/pic08.jpg (HTTP 301). Without the flag the server will serve content from /pics/pic08.jpg while the browser URL remains /images/pic08.jpg.
Helpful reference table Resources and further reading
Always test rewrite rules in a staging environment before applying them to production. Regular expressions can be too broad or miss edge cases; validating behavior with multiple test URLs helps prevent unexpected redirects or broken resources.
Summary
  • Use rewrite to preserve legacy URLs when reorganizing site paths.
  • Choose between internal rewrites (transparent to the user) and redirects (inform client and search engines).
  • Test thoroughly and monitor caches when using permanent redirects.

Watch Video

Practice Lab