{"id":16457,"date":"2019-04-03T08:01:47","date_gmt":"2019-04-03T08:01:47","guid":{"rendered":"https:\/\/www.hostinger.com\/tutorials\/?p=16457"},"modified":"2025-03-05T03:44:31","modified_gmt":"2025-03-05T03:44:31","slug":"nginx-redirect","status":"publish","type":"post","link":"\/in\/tutorials\/nginx-redirect","title":{"rendered":"How to create temporary and permanent NGINX redirects"},"content":{"rendered":"<p>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.<\/p><p>NGINX supports two types of redirects: <strong>permanent redirects<\/strong> (HTTP <strong>301<\/strong>), which indicate permanent URL changes, and <strong>temporary redirects<\/strong> (HTTP <strong>302<\/strong>), which are used for short-term redirections.<\/p><p>In this article, we&rsquo;ll guide you through setting up temporary and permanent redirects in NGINX. You&rsquo;ll learn to use directives like <strong>return<\/strong>, <strong>rewrite<\/strong>, and <strong>try_files<\/strong>, explore common use cases, and implement best practices to avoid issues like redirect loops.<\/p><p>By the end, you&rsquo;ll be able to refine your website&rsquo;s configuration for better traffic management.<\/p><p class=\"has-text-align-center\"><a href=\"https:\/\/assets.hostinger.com\/content\/tutorials\/pdf\/HTTP-Status-Codes-Cheat-Sheet.pdf\" target=\"_blank\" rel=\"noreferrer noopener\">Download comprehensive HTTP status codes cheat sheet<\/a><\/p><p>\n\n\n\n\n\n\n<\/p><h2 class=\"wp-block-heading\" id=\"h-prerequisites-for-creating-nginx-redirects\">Prerequisites for creating NGINX redirects<\/h2><p>Before setting up URL redirects in NGINX, make sure your server meets the following requirements:<\/p><ul class=\"wp-block-list\">\n<li><strong>Permissions to modify server configurations<\/strong> &ndash; you need administrative or sudo privileges to access and edit NGINX configuration files. If you use a <a href=\"\/in\/vps-hosting\">virtual private server (VPS) plan from Hostinger<\/a>, don&rsquo;t worry; we grant you full root access to modify your server as needed.<\/li>\n\n\n\n<li><strong>NGINX installed<\/strong> &ndash; verify that <a href=\"\/in\/tutorials\/what-is-nginx\">NGINX<\/a> is installed and running on your server. Use the <strong>sudo systemctl status nginx<\/strong> command to confirm its status. If NGINX is not there, install it with:<\/li>\n<\/ul><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">sudo apt update\nsudo apt install nginx<\/pre><ul class=\"wp-block-list\">\n<li><strong>Access to the configuration file<\/strong> &ndash; locate the main NGINX configuration file, typically found in the <strong>\/etc\/nginx\/nginx.conf<\/strong> directory. For individual sites, you&rsquo;ll find configuration files in <strong>\/etc\/nginx\/sites-available\/<\/strong>.<\/li>\n\n\n\n<li><strong>Basic understanding of NGINX syntax<\/strong> &ndash; familiarize yourself with the basic structure of NGINX directives and variables, including:\n<ul class=\"wp-block-list\">\n<li><strong>server<\/strong> &ndash; defines a server block that manages incoming requests for a specific domain or IP address.<\/li>\n\n\n\n<li><strong>location<\/strong> &ndash; specifies configurations for specific URIs or file paths.<\/li>\n\n\n\n<li><strong>$request_uri<\/strong> &ndash; captures the full original URI from the client&rsquo;s request.<\/li>\n\n\n\n<li><strong>$host<\/strong> &ndash; refers to the requested hostname or domain.<\/li>\n\n\n\n<li><strong>$query_string<\/strong> &ndash; represents any query parameters in the URL.<\/li>\n<\/ul>\n<\/li>\n\n\n\n<li><strong>Domain and DNS setup<\/strong> &ndash; make sure your <a href=\"\/in\/tutorials\/dns\/how-to-point-domain-to-vps\">domain points to the correct server IP address<\/a> using accurate DNS records.<\/li>\n\n\n\n<li><strong>Configuration file backups <\/strong>&ndash; always back up your existing configuration files to prevent data loss in case of errors. Use the following command:<\/li>\n<\/ul><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">sudo cp \/etc\/nginx\/nginx.conf \/etc\/nginx\/nginx.conf.bak<\/pre><?xml encoding=\"utf-8\" ?><figure class=\"wp-block-image size-large\"><a href=\"\/in\/vps-hosting\" target=\"_blank\" rel=\"noreferrer noopener\"><img decoding=\"async\" width=\"1024\" height=\"300\" src=\"https:\/\/www.hostinger.com\/tutorials\/wp-content\/uploads\/sites\/2\/2023\/02\/VPS-hosting-banner-1024x300.png\" alt=\"\" class=\"wp-image-77934\" srcset=\"https:\/\/www.hostinger.com\/in\/tutorials\/wp-content\/uploads\/sites\/52\/2023\/02\/VPS-hosting-banner.png 1024w, https:\/\/www.hostinger.com\/in\/tutorials\/wp-content\/uploads\/sites\/52\/2023\/02\/VPS-hosting-banner-300x88.png 300w, https:\/\/www.hostinger.com\/in\/tutorials\/wp-content\/uploads\/sites\/52\/2023\/02\/VPS-hosting-banner-150x44.png 150w, https:\/\/www.hostinger.com\/in\/tutorials\/wp-content\/uploads\/sites\/52\/2023\/02\/VPS-hosting-banner-768x225.png 768w\" sizes=\"(max-width: 1024px) 100vw, 1024px\" \/><\/a><\/figure><h2 class=\"wp-block-heading\" id=\"h-implementing-nginx-redirects\">Implementing NGINX redirects<\/h2><p>To configure NGINX redirects, you&rsquo;ll use three key directives: <strong>return<\/strong>, <strong>rewrite<\/strong>, and <strong>try_files<\/strong>. Each serves a specific purpose for effective URL redirection.<\/p><h3 class=\"wp-block-heading\" id=\"h-using-the-return-directive\">Using the return directive<\/h3><p>The <strong>return<\/strong> directive is the simplest and most efficient way to create redirects. It&rsquo;s ideal for scenarios like redirecting a URL or an entire domain. This directive also processes redirects faster as it avoids unnecessary complexity.<\/p><p><strong>return<\/strong> immediately stops processing further instructions and sends the specified <a href=\"\/in\/tutorials\/http-status-codes\">HTTP status code<\/a> and destination URL to the client. Its basic syntax is as follows:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">return [status code] [URL];<\/pre><ul class=\"wp-block-list\">\n<li><strong>[status code]<\/strong> &ndash; Specify <strong>301<\/strong> for permanent or <strong>302<\/strong> for temporary redirects.<\/li>\n\n\n\n<li><strong>[URL]<\/strong> &ndash; Define the target URL, including corresponding NGINX variables like <strong>$request_uri<\/strong> or <strong>$host<\/strong>.<\/li>\n<\/ul><p>For example, to <a href=\"\/in\/tutorials\/how-to-redirect-a-domain\">redirect from an old domain to a new one<\/a>:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">server {\nlisten 80;\nserver_name www.old-domain.tld;\nreturn 301 https:\/\/www.new-domain.tld$request_uri;\n}<\/pre><ul class=\"wp-block-list\">\n<li><strong>301<\/strong> permanently redirects visitors from <strong>www.old-domain.tld<\/strong> to <strong>https:\/\/www.new-domain.tld<\/strong>.<\/li>\n\n\n\n<li><strong>$request_uri<\/strong> preserves the original path and query string.<\/li>\n<\/ul><p>You can also use <strong>return<\/strong> to redirect a single page like this:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">location \/old-page {\nreturn 301 \/new-page;\n}<\/pre><ul class=\"wp-block-list\">\n<li><strong>301<\/strong> redirects users accessing <strong>\/old-page<\/strong> to <strong>\/new-page<\/strong> within the same domain.<\/li>\n<\/ul><h3 class=\"wp-block-heading\" id=\"h-using-the-rewrite-directive\">Using the rewrite directive<\/h3><p>The <strong>rewrite<\/strong> directive lets you perform more complex redirects using regular expressions (<strong>regex<\/strong>), which match patterns in the original URL and transform them into new URLs.<\/p><p>It&rsquo;s best for cases where <strong>return<\/strong> is insufficient, such as dynamically redirecting URLs based on specific patterns or conditions. While <strong>rewrite<\/strong> is powerful, improper usage can lead to problems like redirect loops, so use it carefully.<\/p><p>Here&rsquo;s its basic syntax:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">rewrite regex replacement [flag];<\/pre><ul class=\"wp-block-list\">\n<li><strong>regex<\/strong> &ndash; defines the pattern to match the original URL.<\/li>\n\n\n\n<li><strong>replacement<\/strong> &ndash; specifies the target URL or path.<\/li>\n\n\n\n<li><strong>flag<\/strong> &ndash; optional; controls <strong>rewrite<\/strong>&rsquo;s behavior. Common flags include:\n<ul class=\"wp-block-list\">\n<li><strong>last<\/strong> &ndash; stops processing further rewrite rules.<\/li>\n\n\n\n<li><strong>redirect<\/strong> &ndash; sends a temporary redirect.<\/li>\n\n\n\n<li><strong>permanent<\/strong> &ndash; sends a permanent redirect.<\/li>\n<\/ul>\n<\/li>\n<\/ul><p>For example, to redirect a URL based on a pattern:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">location \/ {\nrewrite ^\/old\/(.*)$ \/new\/$1 permanent;\n}<\/pre><ul class=\"wp-block-list\">\n<li>The regex <strong>^\/old\/(.*)$<\/strong> matches any URL starting with <strong>\/old\/ <\/strong>and captures the rest of the path.<\/li>\n\n\n\n<li><strong>$1<\/strong> refers to the captured group, appending to <strong>\/new\/<\/strong>.<\/li>\n<\/ul><p>Another example adds a trailing slash to URLs:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">rewrite ^([^.]*[^\/])$ $1\/ permanent;<\/pre><ul class=\"wp-block-list\">\n<li><strong>^([^.]*[^\/])$<\/strong> matches URLs without a trailing slash.<\/li>\n\n\n\n<li><strong>$1\/<\/strong> appends a slash to the matched URL.<\/li>\n<\/ul><p>In contrast, you can redirect URLs with a trailing slash to their non-slash versions:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">rewrite ^\/(.*)\/$ \/$1 permanent;<\/pre><ul class=\"wp-block-list\">\n<li><strong>^\/(.*)\/$<\/strong> matches URLs with a trailing slash.<\/li>\n<\/ul><p>\n\n\n<div class=\"protip\">\n                    <h4 class=\"title\">Pro tip<\/h4>\n                    <p>When choosing <strong>rewrite<\/strong>, append the <strong>permanent<\/strong> flag for SEO-friendly redirects and use <strong>last<\/strong> for internal rewrites.<\/p>\n                <\/div>\n\n\n\n<\/p><h3 class=\"wp-block-heading\" id=\"h-using-the-try-files-directive\">Using the try_files directive<\/h3><p>With <strong>try_files<\/strong>, you can check for the existence of specific files or directories before serving a response or redirecting traffic. It&rsquo;s beneficial for dynamic websites, fallback configurations, or redirecting requests when files are missing.<\/p><p>The <strong>try_files<\/strong> directive uses this syntax:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">try_files path1 path2 ... fallback;<\/pre><ul class=\"wp-block-list\">\n<li><strong>path1<\/strong> <strong>path2<\/strong> &ndash; define the file or directory paths NGINX will check in order.<\/li>\n\n\n\n<li><strong>fallback<\/strong> &ndash; specifies the action or URL to take if no defined paths exist.<\/li>\n<\/ul><p>Here&rsquo;s an example of redirecting requests for nonexistent files to a custom error page:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">location \/ {\ntry_files $uri $uri\/ \/404.html;\n}<\/pre><ul class=\"wp-block-list\">\n<li><strong>$uri<\/strong> checks if the requested file exists.<\/li>\n\n\n\n<li><strong>$uri\/ <\/strong>checks if a directory with the requested name exists.<\/li>\n\n\n\n<li><strong>\/404.html<\/strong> is served if neither exists.<\/li>\n<\/ul><p>Similarly, to redirect all missing files to your website&rsquo;s homepage:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">location \/ {\ntry_files $uri $uri\/ \/index.html;\n}<\/pre><ul class=\"wp-block-list\">\n<li><strong>\/index.html<\/strong> serves as the fallback if no file or directory matching the request exists.<\/li>\n<\/ul><p>If you want to redirect missing <strong>PHP<\/strong> files to an error handler:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">location ~ \\.php$ {\ntry_files $uri \/error-handler.php;\n}<\/pre><ul class=\"wp-block-list\">\n<li>The <strong>regex ~ \\.php$<\/strong> matches all <strong>PHP<\/strong> requests.<\/li>\n\n\n\n<li><strong>\/error-handler.php<\/strong> handles requests for missing <strong>PHP<\/strong> files.<\/li>\n<\/ul><h2 class=\"wp-block-heading\" id=\"h-nginx-redirect-use-cases\">NGINX redirect use cases<\/h2><p>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.<\/p><h3 class=\"wp-block-heading\" id=\"h-redirecting-from-http-to-https\">Redirecting from HTTP to HTTPS<\/h3><p>Redirecting HTTP traffic to HTTPS improves your website&rsquo;s security and builds user trust. It also ensures search engines recognize your site as secure, which can boost SEO rankings.<\/p><p>The following example demonstrates how to set up an HTTP to HTTPS redirect using the <strong>return<\/strong> directive:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">server {\nlisten 80;\nserver_name domain.tld www.domain.tld;\nreturn 301 https:\/\/$host$request_uri;\n}<\/pre><ul class=\"wp-block-list\">\n<li><strong>listen 80<\/strong> listens for incoming HTTP traffic on port <strong>80<\/strong>.<\/li>\n\n\n\n<li><strong>server_name domain.tld www.domain.tld<\/strong> specifies the domain names this server block handles.<\/li>\n<\/ul><p>\n\n\n<div class=\"protip\">\n                    <h4 class=\"title\">Suggested reading<\/h4>\n                    <p>Make sure you've set up an SSL certificate on your server before enabling the redirect. Learn <a href=\"https:\/\/support.hostinger.com\/en\/articles\/6865487-how-to-install-ssl-on-vps-using-certbot\" target=\"_blank\" rel=\"noopener\">how to install a free SSL on your VPS<\/a> if you haven't done so already.<\/p>\n                <\/div>\n\n\n\n<\/p><h3 class=\"wp-block-heading\" id=\"h-redirecting-non-www-to-www\">Redirecting non-WWW to WWW<\/h3><p>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:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">server {\nlisten 80;\nserver_name domain.tld;\nreturn 301 http:\/\/www.domain.tld$request_uri;\n}<\/pre><ul class=\"wp-block-list\">\n<li><strong>server_name domain.tld<\/strong> matches requests for the non-WWW version of the domain.<\/li>\n<\/ul><p>If your site uses HTTPS, add a similar configuration to redirect non-WWW traffic over HTTPS:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">server {\nlisten 443 ssl;\nserver_name domain.tld;\nreturn 301 https:\/\/www.domain.tld$request_uri;\n}<\/pre><ul class=\"wp-block-list\">\n<li><strong>listen 443 ssl<\/strong> listens for HTTPS traffic.<\/li>\n<\/ul><h3 class=\"wp-block-heading\" id=\"h-redirecting-to-a-maintenance-page\">Redirecting to a maintenance page<\/h3><p>Redirecting traffic to a maintenance page is common during site updates or temporary downtime. Using a <strong>location<\/strong> block, you can easily configure an NGINX URL redirect to inform visitors of ongoing maintenance.<\/p><p>For instance, to redirect all traffic to a maintenance page:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">server {\nlisten 80;\nserver_name domain.tld www.domain.tld;\nlocation \/ {\nreturn 302 \/maintenance.html;\n}\nlocation \/maintenance.html {\nroot \/var\/www\/html;\n}\n}<\/pre><ul class=\"wp-block-list\">\n<li><strong>location \/<\/strong> matches all incoming requests and redirects them to <strong>\/maintenance.html<\/strong> using a temporary (<strong>302<\/strong>) redirect.<\/li>\n\n\n\n<li><strong>location \/maintenance.html<\/strong> specifies the maintenance page file&rsquo;s location. In this case, it&rsquo;s in the <strong>\/var\/www\/html<\/strong> directory.<\/li>\n<\/ul><h3 class=\"wp-block-heading\" id=\"h-setting-up-conditional-redirects\">Setting up conditional redirects<\/h3><p>Conditional redirects in NGINX let you redirect traffic based on specific conditions, such as user agents or IP addresses. Use the <strong>if<\/strong> directive within a server or location block to do so.<\/p><p>The following example redirects mobile users to a mobile version of your site:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">server {\nlisten 80;\nserver_name domain.tld www.domain.tld;\nif ($http_user_agent ~* \"Mobile\") {\nreturn 302 https:\/\/m.domain.tld$request_uri;\n}\n}<\/pre><ul class=\"wp-block-list\">\n<li><strong>$http_user_agent<\/strong> matches the user agent string of the visitor&rsquo;s browser or device.<\/li>\n\n\n\n<li>The <strong>~* &ldquo;Mobile&rdquo;<\/strong> condition matches user agents containing <strong>Mobile<\/strong>, which is case-insensitive.<\/li>\n<\/ul><p>Another example displays how to block or redirect specific IPs:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">server {\nlisten 80;\nserver_name domain.tld;\nif ($remote_addr = 192.168.1.1) {\nreturn 403;\n}\n}<\/pre><ul class=\"wp-block-list\">\n<li><strong>$remote_addr<\/strong> matches the visitor&rsquo;s IP address.<\/li>\n\n\n\n<li>The <strong>return 403<\/strong> directive blocks access by returning a <strong>Forbidden<\/strong> (<strong>403<\/strong>) response code.<\/li>\n<\/ul><h3 class=\"wp-block-heading\" id=\"h-redirecting-with-query-parameters\">Redirecting with query parameters<\/h3><p>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 <strong>if<\/strong> or <strong>rewrite <\/strong>directives, combined with variables like <strong>$request_uri<\/strong> and <strong>$arg_<\/strong>.<\/p><p>For example, to redirect a URL while preserving query parameters:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">location \/old-page {\nreturn 301 \/new-page?$query_string;\n}<\/pre><ul class=\"wp-block-list\">\n<li><strong>$query_string<\/strong> preserves the original query parameters in the redirected URL.<\/li>\n\n\n\n<li>For example, <strong>\/old-page?promo=true<\/strong> redirects to <strong>\/new-page?promo=true<\/strong>.<\/li>\n<\/ul><p>Meanwhile, to redirect visitors based on a specific query parameter:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">server {\nlisten 80;\nserver_name domain.tld;\nif ($arg_promo = \"true\") {\nreturn 301 \/promo-page;\n}\n}<\/pre><ul class=\"wp-block-list\">\n<li><strong>$arg_promo<\/strong> matches the <strong>promo<\/strong> query string in the URL.<\/li>\n\n\n\n<li>If the query string equals true, <strong>visitors<\/strong> are redirected to <strong>\/promo-page<\/strong>.<\/li>\n<\/ul><h2 class=\"wp-block-heading\" id=\"h-nginx-redirects-best-practices\">NGINX redirects best practices<\/h2><p>Follow these best practices when setting up NGINX redirects to achieve optimal performance, avoid errors, and maintain a smooth user experience:<\/p><p><strong>Avoid redirect loops<\/strong><\/p><p>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.<\/p><p>This example is not safe because it redirects traffic back to itself:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">server {\nlisten 80;\nserver_name domain.tld;\nreturn 301 https:\/\/domain.tld$request_uri;\n}<\/pre><p>Conversely, below is an example of a safe redirect:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">server {\nlisten 80;\nserver_name www.domain.tld;\nreturn 301 https:\/\/domain.tld$request_uri;\n}<\/pre><p><strong>Use wildcards or regex only if necessary<\/strong><\/p><p>While wildcards and regular expressions provide flexibility, they can complicate configurations and impact performance. Use them only when simpler options, like the <strong>return<\/strong> directive, can&rsquo;t handle your requirements.<\/p><p>For instance, avoid overly broad patterns like this:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">location ~ .* {\nreturn 301 \/new-page;\n}<\/pre><p>Instead, use specific patterns or conditions, as shown below:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">location ~ ^\/old-page[0-9]+$ {\nreturn 301 \/new-page;\n}<\/pre><p><strong>Combine redirect rules where possible<\/strong><\/p><p>Consolidating similar redirects into a single block minimizes directives and improves clarity. For example:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">location ~ ^\/(old-page1|old-page2|old-page3)$ {\nreturn 301 \/new-page;\n}<\/pre><p><strong>Minimize chained redirects<\/strong><\/p><p>Chaining multiple redirects slows down page loading and negatively impacts SEO. Always redirect traffic directly to its final destination. For instance, instead of chaining:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/page1 -&gt; \/page2 -&gt; \/page3<\/pre><p>Use a direct redirect like this:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">\/page1 -&gt; \/page3<\/pre><p><strong>Test redirect rules before and after deploying<\/strong><\/p><p>Always validate your redirects so that they&rsquo;ll behave as intended. Use these commands to check for syntax errors before reloading your configuration:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">sudo nginx -t\nsudo systemctl reload nginx<\/pre><p>Hostinger VPS customers can also use <strong>Kodee<\/strong> to identify syntax errors in their NGINX configuration. Simply ask, &ldquo;Can you check my current NGINX configuration for any errors?&rdquo; and the tool will respond like this:<\/p><div class=\"wp-block-image\">\n<figure data-wp-context='{\"imageId\":\"69e01327247b5\"}' data-wp-interactive=\"core\/image\" class=\"aligncenter size-large wp-lightbox-container\"><img decoding=\"async\" data-wp-class--hide=\"state.isContentHidden\" data-wp-class--show=\"state.isContentVisible\" data-wp-init=\"callbacks.setButtonStyles\" data-wp-on-async--click=\"actions.showLightbox\" data-wp-on-async--load=\"callbacks.setButtonStyles\" data-wp-on-async-window--resize=\"callbacks.setButtonStyles\" src=\"\/tutorials\/wp-content\/uploads\/sites\/2\/2021\/09\/hpanel-vps-kodee-1024x339.png\" alt=\"Kodee responds to a question about NGINX configuration\"><button class=\"lightbox-trigger\" type=\"button\" aria-haspopup=\"dialog\" aria-label=\"Enlarge\" data-wp-init=\"callbacks.initTriggerButton\" data-wp-on-async--click=\"actions.showLightbox\" data-wp-style--right=\"state.imageButtonRight\" data-wp-style--top=\"state.imageButtonTop\">\n\t\t\t<svg xmlns=\"http:\/\/www.w3.org\/2000\/svg\" width=\"12\" height=\"12\" fill=\"none\" viewbox=\"0 0 12 12\">\n\t\t\t\t<path fill=\"#fff\" d=\"M2 0a2 2 0 0 0-2 2v2h1.5V2a.5.5 0 0 1 .5-.5h2V0H2Zm2 10.5H2a.5.5 0 0 1-.5-.5V8H0v2a2 2 0 0 0 2 2h2v-1.5ZM8 12v-1.5h2a.5.5 0 0 0 .5-.5V8H12v2a2 2 0 0 1-2 2H8Zm2-12a2 2 0 0 1 2 2v2h-1.5V2a.5.5 0 0 0-.5-.5H8V0h2Z\"><\/path>\n\t\t\t<\/svg>\n\t\t<\/button><\/figure><\/div><p>Alternatively, tools like <a href=\"\/in\/tutorials\/curl-command-with-examples-linux\">curl<\/a> can verify HTTP status codes and redirected URLs:<\/p><pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">curl -I http:\/\/domain.tld\/old-page<\/pre><p>After deployment, use SEO tools like <a href=\"https:\/\/search.google.com\/search-console\/about\" target=\"_blank\" rel=\"noopener\">Google Search Console<\/a> or <a href=\"https:\/\/www.screamingfrog.co.uk\/seo-spider\" target=\"_blank\" rel=\"noopener\">Screaming Frog<\/a> to ensure no broken links or redirect loops.<\/p><p>\n\n\n<div class=\"protip\">\n                    <h4 class=\"title\">Suggested reading<\/h4>\n                    <p>Besides setting up redirects, you can also <a href=\"\/in\/tutorials\/how-to-set-up-nginx-reverse-proxy\">use NGINX to configure a reverse proxy<\/a>. Read our article to learn more.<\/p>\n                <\/div>\n\n\n\n<\/p><h2 class=\"wp-block-heading\" id=\"h-conclusion\">Conclusion<\/h2><p>In this article, we&rsquo;ve explained how to set up various NGINX redirects, including redirects from HTTP to HTTPS and from non-WWW to WWW. You&rsquo;ve also discovered best practices, such as how to avoid redirect loops, use regex wisely, and thoroughly test your redirects.<\/p><p>Furthermore, we&rsquo;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.<\/p><p>If you still have questions about NGINX server-side redirects, feel free to use the comment box below.<\/p><h2 class=\"wp-block-heading\" id=\"h-nginx-redirect-faq\">NGINX redirect FAQ<\/h2><div class=\"schema-faq wp-block-yoast-faq-block\"><div class=\"schema-faq-section\" id=\"faq-question-1733444278385\"><h3 class=\"schema-faq-question\">What is an NGINX redirect?<\/h3> <p class=\"schema-faq-answer\">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 <strong>301<\/strong> (permanent) or <strong>302<\/strong> (temporary).<\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1733444290515\"><h3 class=\"schema-faq-question\">How do I configure a simple redirect in NGINX?<\/h3> <p class=\"schema-faq-answer\">To configure a simple redirect in NGINX, use the <strong>return<\/strong> directive within the relevant <strong>server<\/strong> block. For example:<br><strong>server {<br>listen 80;<br>server_name old-domain.tld;<br>return 301 https:\/\/new-domain.tld$request_uri;<br>}<\/strong><\/p> <\/div> <div class=\"schema-faq-section\" id=\"faq-question-1733444324399\"><h3 class=\"schema-faq-question\">What syntax do I use for a 301 redirect?<\/h3> <p class=\"schema-faq-answer\">For a <strong>301<\/strong> redirect in NGINX, use the following syntax:<br><strong>return 301 https:\/\/new-domain.tld$request_uri;<br><\/strong>This permanently redirects visitors from the old URL to the new destination.<\/p> <\/div> <\/div>\n","protected":false},"excerpt":{"rendered":"<p>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, [&#8230;]<\/p>\n<p><a class=\"btn btn-secondary understrap-read-more-link\" href=\"\/in\/tutorials\/nginx-redirect\">Read More&#8230;<\/a><\/p>\n","protected":false},"author":411,"featured_media":87036,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"","rank_math_description":"","rank_math_focus_keyword":"","footnotes":""},"categories":[22642,22640],"tags":[],"class_list":["post-16457","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-pre-installed-applications","category-vps"],"hreflangs":[{"locale":"en-US","link":"https:\/\/www.hostinger.com\/tutorials\/nginx-redirect","default":0},{"locale":"en-UK","link":"https:\/\/www.hostinger.com\/uk\/tutorials\/nginx-redirect","default":0},{"locale":"en-MY","link":"https:\/\/www.hostinger.com\/my\/tutorials\/nginx-redirect","default":0},{"locale":"en-PH","link":"https:\/\/www.hostinger.com\/ph\/tutorials\/nginx-redirect","default":0},{"locale":"en-IN","link":"https:\/\/www.hostinger.com\/in\/tutorials\/nginx-redirect","default":0},{"locale":"en-CA","link":"https:\/\/www.hostinger.com\/ca\/tutorials\/nginx-redirect","default":0},{"locale":"en-AU","link":"https:\/\/www.hostinger.com\/au\/tutorials\/nginx-redirect","default":0},{"locale":"en-NG","link":"https:\/\/www.hostinger.com\/ng\/tutorials\/nginx-redirect","default":0}],"_links":{"self":[{"href":"https:\/\/www.hostinger.com\/in\/tutorials\/wp-json\/wp\/v2\/posts\/16457","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.hostinger.com\/in\/tutorials\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.hostinger.com\/in\/tutorials\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.hostinger.com\/in\/tutorials\/wp-json\/wp\/v2\/users\/411"}],"replies":[{"embeddable":true,"href":"https:\/\/www.hostinger.com\/in\/tutorials\/wp-json\/wp\/v2\/comments?post=16457"}],"version-history":[{"count":16,"href":"https:\/\/www.hostinger.com\/in\/tutorials\/wp-json\/wp\/v2\/posts\/16457\/revisions"}],"predecessor-version":[{"id":124503,"href":"https:\/\/www.hostinger.com\/in\/tutorials\/wp-json\/wp\/v2\/posts\/16457\/revisions\/124503"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.hostinger.com\/in\/tutorials\/wp-json\/wp\/v2\/media\/87036"}],"wp:attachment":[{"href":"https:\/\/www.hostinger.com\/in\/tutorials\/wp-json\/wp\/v2\/media?parent=16457"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.hostinger.com\/in\/tutorials\/wp-json\/wp\/v2\/categories?post=16457"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.hostinger.com\/in\/tutorials\/wp-json\/wp\/v2\/tags?post=16457"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}