rewrite directive to transparently redirect an old URL path to a new one. This approach preserves existing bookmarks and SEO value by issuing a permanent (301) redirect.
Scenario
Your siteexample.com originally served images from:
/images to /pics, you want to redirect all traffic from /images/... to /pics/... without breaking links. A suitable rewrite rule is:
/images/ and issues a 301 redirect to /pics/....
Prerequisites
- A running Nginx server (≥1.14)
- SSH access to the server
- Root or sudo privileges
- A staging environment for testing
Always test changes in a staging environment before deploying to production to avoid downtime.
1. Prepare the Content Directory
On the Nginx server, duplicate theimages/ folder under the document root (/var/www/html):
2. Test Before Rewriting
Ensure Nginx is running and serving files without any rewrite rules:- Open your browser and visit:
http://example.com/images/pic10.jpg - You should see the image load directly from
/images/pic10.jpg.
3. Review Initial Nginx Configuration
Open your server block configuration forexample.com (commonly in /etc/nginx/sites-available/example):
4. Add the Rewrite Directive
Edit the sameserver block and insert the rewrite rule before try_files:
A typo in the regex or placement of
rewrite can lead to redirect loops. Double-check the pattern and test thoroughly.5. Verify the Rewrite
To avoid cached redirects, open an incognito/private browser window and navigate to:Quick Reference
| Step | Action | Command / Pattern |
|---|---|---|
| 1 | Duplicate directory | cp -R images/ pics/ |
| 2 | Verify directories | ls -l /var/www/html |
| 3 | Review current Nginx server block | /etc/nginx/sites-available/example |
| 4 | Add rewrite rule before try_files | rewrite ^/images/(.*)$ /pics/$1 permanent; |
| 5 | Test the redirect in private browser | Visit /images/pic08.jpg |
Conclusion
Using Nginx’srewrite directive with regular expressions allows seamless URL remapping and preserves SEO by issuing 301 redirects. Always:
- Validate your Nginx configuration (
nginx -t) - Reload Nginx to apply changes
- Test rewrites in a staging environment