How to create temporary and permanent NGINX redirects
An NGINX redirect is a configuration that routes web traffic from one URL to another, so visitors and search engines can land on the correct destination. Redirects are important for maintaining SEO rankings, avoiding duplicate content, and improving user experience.
NGINX supports two types of redirects: permanent redirects (HTTP 301), which indicate permanent URL changes, and temporary redirects (HTTP 302), which are used for short-term redirections.
In this article, we’ll guide you through setting up temporary and permanent redirects in NGINX. You’ll learn to use directives like return, rewrite, and try_files, explore common use cases, and implement best practices to avoid issues like redirect loops.
By the end, you’ll be able to refine your website’s configuration for better traffic management.
Download comprehensive HTTP status codes cheat sheet
Prerequisites for creating NGINX redirects
Before setting up URL redirects in NGINX, make sure your server meets the following requirements:
- Permissions to modify server configurations – you need administrative or sudo privileges to access and edit NGINX configuration files. If you use a virtual private server (VPS) plan from Hostinger, don’t worry; we grant you full root access to modify your server as needed.
- NGINX installed – verify that NGINX is installed and running on your server. Use the sudo systemctl status nginx command to confirm its status. If NGINX is not there, install it with:
sudo apt update sudo apt install nginx
- Access to the configuration file – locate the main NGINX configuration file, typically found in the /etc/nginx/nginx.conf directory. For individual sites, you’ll find configuration files in /etc/nginx/sites-available/.
- Basic understanding of NGINX syntax – familiarize yourself with the basic structure of NGINX directives and variables, including:
- server – defines a server block that manages incoming requests for a specific domain or IP address.
- location – specifies configurations for specific URIs or file paths.
- $request_uri – captures the full original URI from the client’s request.
- $host – refers to the requested hostname or domain.
- $query_string – represents any query parameters in the URL.
- Domain and DNS setup – make sure your domain points to the correct server IP address using accurate DNS records.
- Configuration file backups – always back up your existing configuration files to prevent data loss in case of errors. Use the following command:
sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak
Implementing NGINX redirects
To configure NGINX redirects, you’ll use three key directives: return, rewrite, and try_files. Each serves a specific purpose for effective URL redirection.
Using the return directive
The return directive is the simplest and most efficient way to create redirects. It’s ideal for scenarios like redirecting a URL or an entire domain. This directive also processes redirects faster as it avoids unnecessary complexity.
return immediately stops processing further instructions and sends the specified HTTP status code and destination URL to the client. Its basic syntax is as follows:
return [status code] [URL];
- [status code] – Specify 301 for permanent or 302 for temporary redirects.
- [URL] – Define the target URL, including corresponding NGINX variables like $request_uri or $host.
For example, to redirect from an old domain to a new one:
server { listen 80; server_name www.old-domain.tld; return 301 https://www.new-domain.tld$request_uri; }
- 301 permanently redirects visitors from www.old-domain.tld to https://www.new-domain.tld.
- $request_uri preserves the original path and query string.
You can also use return to redirect a single page like this:
location /old-page { return 301 /new-page; }
- 301 redirects users accessing /old-page to /new-page within the same domain.
Using the rewrite directive
The rewrite directive lets you perform more complex redirects using regular expressions (regex), which match patterns in the original URL and transform them into new URLs.
It’s best for cases where return is insufficient, such as dynamically redirecting URLs based on specific patterns or conditions. While rewrite is powerful, improper usage can lead to problems like redirect loops, so use it carefully.
Here’s its basic syntax:
rewrite regex replacement [flag];
- regex – defines the pattern to match the original URL.
- replacement – specifies the target URL or path.
- flag – optional; controls rewrite’s behavior. Common flags include:
- last – stops processing further rewrite rules.
- redirect – sends a temporary redirect.
- permanent – sends a permanent redirect.
For example, to redirect a URL based on a pattern:
location / { rewrite ^/old/(.*)$ /new/$1 permanent; }
- The regex ^/old/(.*)$ matches any URL starting with /old/ and captures the rest of the path.
- $1 refers to the captured group, appending to /new/.
Another example adds a trailing slash to URLs:
rewrite ^([^.]*[^/])$ $1/ permanent;
- ^([^.]*[^/])$ matches URLs without a trailing slash.
- $1/ appends a slash to the matched URL.
In contrast, you can redirect URLs with a trailing slash to their non-slash versions:
rewrite ^/(.*)/$ /$1 permanent;
- ^/(.*)/$ matches URLs with a trailing slash.
Pro tip
When choosing rewrite, append the permanent flag for SEO-friendly redirects and use last for internal rewrites.
Using the try_files directive
With try_files, you can check for the existence of specific files or directories before serving a response or redirecting traffic. It’s beneficial for dynamic websites, fallback configurations, or redirecting requests when files are missing.
The try_files directive uses this syntax:
try_files path1 path2 ... fallback;
- path1 path2 – define the file or directory paths NGINX will check in order.
- fallback – specifies the action or URL to take if no defined paths exist.
Here’s an example of redirecting requests for nonexistent files to a custom error page:
location / { try_files $uri $uri/ /404.html; }
- $uri checks if the requested file exists.
- $uri/ checks if a directory with the requested name exists.
- /404.html is served if neither exists.
Similarly, to redirect all missing files to your website’s homepage:
location / { try_files $uri $uri/ /index.html; }
- /index.html serves as the fallback if no file or directory matching the request exists.
If you want to redirect missing PHP files to an error handler:
location ~ \.php$ { try_files $uri /error-handler.php; }
- The regex ~ \.php$ matches all PHP requests.
- /error-handler.php handles requests for missing PHP files.
NGINX redirect use cases
NGINX redirects serve various purposes, from strengthening security to improving user experience. Here are five common use cases and instructions on how to implement them.
Redirecting from HTTP to HTTPS
Redirecting HTTP traffic to HTTPS improves your website’s security and builds user trust. It also ensures search engines recognize your site as secure, which can boost SEO rankings.
The following example demonstrates how to set up an HTTP to HTTPS redirect using the return directive:
server { listen 80; server_name domain.tld www.domain.tld; return 301 https://$host$request_uri; }
- listen 80 listens for incoming HTTP traffic on port 80.
- server_name domain.tld www.domain.tld specifies the domain names this server block handles.
Suggested reading
Make sure you’ve set up an SSL certificate on your server before enabling the redirect. Learn how to install a free SSL on your VPS if you haven’t done so already.
Redirecting non-WWW to WWW
Redirecting non-WWW traffic to the WWW version of your website maintains a consistent URL structure and avoids duplicate content issues. You can achieve this in NGINX by adding a dedicated server block to handle non-WWW requests. For example:
server { listen 80; server_name domain.tld; return 301 http://www.domain.tld$request_uri; }
- server_name domain.tld matches requests for the non-WWW version of the domain.
If your site uses HTTPS, add a similar configuration to redirect non-WWW traffic over HTTPS:
server { listen 443 ssl; server_name domain.tld; return 301 https://www.domain.tld$request_uri; }
- listen 443 ssl listens for HTTPS traffic.
Redirecting to a maintenance page
Redirecting traffic to a maintenance page is common during site updates or temporary downtime. Using a location block, you can easily configure an NGINX URL redirect to inform visitors of ongoing maintenance.
For instance, to redirect all traffic to a maintenance page:
server { listen 80; server_name domain.tld www.domain.tld; location / { return 302 /maintenance.html; } location /maintenance.html { root /var/www/html; } }
- location / matches all incoming requests and redirects them to /maintenance.html using a temporary (302) redirect.
- location /maintenance.html specifies the maintenance page file’s location. In this case, it’s in the /var/www/html directory.
Setting up conditional redirects
Conditional redirects in NGINX let you redirect traffic based on specific conditions, such as user agents or IP addresses. Use the if directive within a server or location block to do so.
The following example redirects mobile users to a mobile version of your site:
server { listen 80; server_name domain.tld www.domain.tld; if ($http_user_agent ~* "Mobile") { return 302 https://m.domain.tld$request_uri; } }
- $http_user_agent matches the user agent string of the visitor’s browser or device.
- The ~* “Mobile” condition matches user agents containing Mobile, which is case-insensitive.
Another example displays how to block or redirect specific IPs:
server { listen 80; server_name domain.tld; if ($remote_addr = 192.168.1.1) { return 403; } }
- $remote_addr matches the visitor’s IP address.
- The return 403 directive blocks access by returning a Forbidden (403) response code.
Redirecting with query parameters
By redirecting URLs with query parameters, you can manage dynamic requests while preserving or modifying specific data in the URL. NGINX makes this possible using the if or rewrite directives, combined with variables like $request_uri and $arg_.
For example, to redirect a URL while preserving query parameters:
location /old-page { return 301 /new-page?$query_string; }
- $query_string preserves the original query parameters in the redirected URL.
- For example, /old-page?promo=true redirects to /new-page?promo=true.
Meanwhile, to redirect visitors based on a specific query parameter:
server { listen 80; server_name domain.tld; if ($arg_promo = "true") { return 301 /promo-page; } }
- $arg_promo matches the promo query string in the URL.
- If the query string equals true, visitors are redirected to /promo-page.
NGINX redirects best practices
Follow these best practices when setting up NGINX redirects to achieve optimal performance, avoid errors, and maintain a smooth user experience:
Avoid redirect loops
Redirect loops occur when a rule unintentionally redirects traffic back to itself or overlaps with other rules. These loops can slow down your server and frustrate users. Prevent redirect loops by using precise conditions in your server or location blocks to avoid conflicts.
This example is not safe because it redirects traffic back to itself:
server { listen 80; server_name domain.tld; return 301 https://domain.tld$request_uri; }
Conversely, below is an example of a safe redirect:
server { listen 80; server_name www.domain.tld; return 301 https://domain.tld$request_uri; }
Use wildcards or regex only if necessary
While wildcards and regular expressions provide flexibility, they can complicate configurations and impact performance. Use them only when simpler options, like the return directive, can’t handle your requirements.
For instance, avoid overly broad patterns like this:
location ~ .* { return 301 /new-page; }
Instead, use specific patterns or conditions, as shown below:
location ~ ^/old-page[0-9]+$ { return 301 /new-page; }
Combine redirect rules where possible
Consolidating similar redirects into a single block minimizes directives and improves clarity. For example:
location ~ ^/(old-page1|old-page2|old-page3)$ { return 301 /new-page; }
Minimize chained redirects
Chaining multiple redirects slows down page loading and negatively impacts SEO. Always redirect traffic directly to its final destination. For instance, instead of chaining:
/page1 -> /page2 -> /page3
Use a direct redirect like this:
/page1 -> /page3
Test redirect rules before and after deploying
Always validate your redirects so that they’ll behave as intended. Use these commands to check for syntax errors before reloading your configuration:
sudo nginx -t sudo systemctl reload nginx
Alternatively, tools like curl can verify HTTP status codes and redirected URLs:
curl -I http://domain.tld/old-page
After deployment, use SEO tools like Google Search Console or Screaming Frog to ensure no broken links or redirect loops.
Suggested reading
Besides setting up redirects, you can also use NGINX to configure a reverse proxy. Read our article to learn more.
Conclusion
In this article, we’ve explained how to set up various NGINX redirects, including redirects from HTTP to HTTPS and from non-WWW to WWW. You’ve also discovered best practices, such as how to avoid redirect loops, use regex wisely, and thoroughly test your redirects.
Furthermore, we’ve covered configuring redirects with query parameters and maintaining clean server blocks. With this knowledge, you can efficiently manage traffic and optimize your server configurations for performance and SEO.
If you still have questions about NGINX server-side redirects, feel free to use the comment box below.
NGINX redirect FAQ
What is an NGINX redirect?
An NGINX redirect is a server-side instruction that sends visitors from one URL to another. It helps manage traffic, improve SEO, and maintain correct routing, typically using status codes like 301 (permanent) or 302 (temporary).
How do I configure a simple redirect in NGINX?
To configure a simple redirect in NGINX, use the return directive within the relevant server block. For example:
server {
listen 80;
server_name old-domain.tld;
return 301 https://new-domain.tld$request_uri;
}
What syntax do I use for a 301 redirect?
For a 301 redirect in NGINX, use the following syntax:
return 301 https://new-domain.tld$request_uri;
This permanently redirects visitors from the old URL to the new destination.
Comments
July 26 2022
How do I redirect old pages of my website (like, /contact-me/, /about-me/, /portfolio.html) to the main domain of mysite.com?
July 28 2022
Hi there! Let's say you wish to redirect /contact-me directory to the main domain in Nginx. For that you would need to use the following output: server{ ... location /contact-me { rewrite ^/contact-me(.*)$ https://www.yourdomainanme.com/$1 redirect; } ... } Hopefully this helps you! ?