Problem: Redirecting Specific URLs in Nginx
Redirecting specific URLs in Nginx is a common task when managing web servers. It involves setting up Nginx to send visitors from one URL to another. This is useful for keeping SEO value, handling old pages, or reorganizing a website.
Common Scenarios for URL Redirection
Website Restructuring
Website restructuring requires redirecting old URLs to new structures. This process helps maintain user experience during site changes. When you update your website's organization, you need to make sure visitors can still find the content they're looking for. By setting up redirects, you guide users to the correct pages on your updated site, reducing confusion and potential loss of traffic.
Tip: Use a Redirect Map
Create a redirect map file to manage multiple redirects efficiently. This file lists old URLs and their corresponding new destinations, making it easier to update and maintain redirects as your site evolves.
Custom URL Shortening
Custom URL shortening is another use for redirects. This technique creates short, memorable URLs that point to longer web addresses. Short URLs are easier to share, especially on platforms with character limits like social media. They also improve link tracking, as you can create unique short URLs for different marketing campaigns or sources. By using Nginx to handle these redirects, you can manage your custom short URLs and direct users to the full, original web addresses.
Example: Creating a Short URL with Nginx
server {
listen 80;
server_name example.com;
location /short1 {
return 301 https://www.example.com/very/long/url/path;
}
}
Setting Up Specific URL Redirects in Nginx
Configuring Nginx Server Blocks
To set up URL redirects in Nginx, you need to work with server blocks. The Nginx configuration file is usually at /etc/nginx/nginx.conf or /usr/local/nginx/conf/nginx.conf. Server blocks are in this file and define how Nginx handles requests for domains or IP addresses.
A basic server block structure:
server {
listen 80;
server_name example.com;
# Configuration directives go here
}
Tip: Use Server Name Directive
When setting up server blocks, use the server_name
directive to specify which domain names or IP addresses the server block should respond to. This allows you to host multiple websites on a single server.
Writing Redirect Rules
To create redirect rules, use the location
directive within a server block. The syntax for a basic redirect:
location /old-url {
return 301 /new-url;
}
For specific URLs, use exact matches:
location = /exact-old-url {
return 301 /exact-new-url;
}
You can use regular expressions for flexible matching:
location ~ ^/old-prefix/(.*)$ {
return 301 /new-prefix/$1;
}
Implementing 301 (Permanent) Redirects
When setting up redirects, you can choose between 301 (permanent) and 302 (temporary) redirects. A 301 redirect tells search engines that the page has moved permanently, while a 302 indicates a temporary move.
The main difference is how search engines treat them:
- 301 redirects: Search engines transfer most of the SEO value from the old URL to the new one.
- 302 redirects: Search engines keep the old URL in their index, assuming the move is temporary.
Using 301 redirects for permanent changes offers SEO benefits:
- It helps maintain search engine rankings for the redirected pages.
- It consolidates link equity from old URLs to new ones.
- It provides a better user experience by directing users to the correct content.
To implement a 301 redirect in Nginx, use this syntax:
return 301 $scheme://newdomain.com$request_uri;
This redirects all requests to a new domain while keeping the original path and query parameters.
Example: Redirecting with Query Parameters
To redirect while preserving query parameters, you can use the following Nginx configuration:
location /old-page {
return 301 /new-page$is_args$args;
}
This will redirect /old-page?param1=value1¶m2=value2
to /new-page?param1=value1¶m2=value2
, keeping all original query parameters intact.
Advanced Redirect Techniques in Nginx
Using Regular Expressions for Dynamic Redirects
Regular expressions in Nginx help you create flexible redirect patterns. These patterns can match multiple URLs and redirect them based on specific parts of the original URL.
To use regular expressions in Nginx redirects, add the ~
symbol before the location pattern:
location ~ ^/old-section/(.*)$ {
return 301 /new-section/$1;
}
This rule redirects any URL starting with /old-section/
to /new-section/
, keeping the rest of the URL path intact.
You can capture multiple parts of the URL:
location ~ ^/category/([^/]+)/([^/]+)$ {
return 301 /new-layout/$1-products/$2;
}
This rule would redirect /category/electronics/laptops
to /new-layout/electronics-products/laptops
.
Tip: Case-Insensitive Matching
To make your regular expression matches case-insensitive, use the ~*
operator instead of ~
. For example:
location ~* ^/old-section/(.*)$ {
return 301 /new-section/$1;
}
This will match URLs regardless of letter case, such as /OLD-SECTION/page
or /Old-Section/Page
.
Handling Query Parameters in Redirects
Preserving or changing query strings during redirection is often needed to maintain functionality or tracking information.
To preserve all query parameters in a redirect, use the $is_args$args
variables:
location /old-page {
return 301 /new-page$is_args$args;
}
This redirect keeps all original query parameters intact.
To change specific query parameters, you can use the set
directive with regular expressions:
location /product {
if ($args ~ ^id=(\d+)) {
set $product_id $1;
return 301 /new-product-page/$product_id;
}
}
This rule extracts the product ID from the query string and includes it in the new URL path.
You can also add new query parameters or change existing ones:
location /search {
return 301 /new-search?source=old&$args;
}
This adds a source=old
parameter to the query string while keeping all original parameters.