How to Redirect a URL Segment in Nginx
Published on: (Updated on: )
You can redirect a URL segment in Nginx, for example, from '/wp-content/uploads/picture.jpg' to '/static/uploads/picture.jpg', with just a single line of code in the Nginx config file. I recently had to do this while migrating a WordPress site to Django, and I'll show you how to accomplish it in a few simple steps.
Remember that changes in server configs are powerful because they affect how your site behaves. This is why it is always important to backup configs before making changes.
1. Find Nginx configuration file: Your Nginx config files live inside the '/etc/nginx/' directory on your server. The specific file you might need is often '/etc/nginx/nginx.conf' or under '/etc/nginx/sites-available/'. This might vary based on your setup.
2. Open the file: Use a text editor like Nano to open the file. If your config is in '/etc/nginx/sites-available/default', you could open it with a command. The command looks like 'sudo nano /etc/nginx/sites-available/default'.
3. Locate the right context: Inside your Nginx configuration, you'll look for the 'server' block or location context where you need to apply the rewrite rule. This is where your website's details are set.
4. Add the Rewrite Rule: Inside the 'server' block or relevant 'location' block, add your rewrite command. It looks like this:
rewrite ^/wp-content/uploads/(.)$ /static/uploads/$1 permanent;
This line of code tells Nginx: "Hey, if you see a URL that starts with '/wp-content/uploads/ followed by anything ('.'), let's change that start to '/static/uploads' but keep whatever came after '/uploads/'". The 'permanent' will ensure that search engines will get a '301' status which signals that the page has permanently moved. If the redirection is temporary, use the following rewrite rule instead for a '302' status:
rewrite ^/wp-content/uploads/(.)$ /static/uploads/$1 redirect;
5. Save and Exit: After adding the rewrite rule, save your changes. If you're using Nano, press 'CTRL+X', then 'Y' to confirm saving, and 'Enter' to exit.
6. Test the Configuration: Before you make your changes live, test if your Nginx configuration is okay. In Ubuntu, you do this with:
sudo nginx -t
If everything's good, you'll see a message saying the syntax is okay and the test is successful.
7. Reload Nginx: To apply your changes, reload Nginx using:
sudo systemctl reload nginx
This makes your new rules take effect without stopping your web server.
8. Check the Redirect: Now, try accessing an image under 'wp-content/uploads/something.jpg'. If everything worked, Nginx will gracefully send you to '/static/uploads/something.jpg'.