Nginx rewrite URL examples with and without redirect address

Nginx can handle the rewrite parameter differently, depending on the destination syntax.

Here are some examples how to define redirects and URL rewrites in Nginx.

Basic redirect (302 Moved Temporarily)

The simplest form to create a redirect is to append the rewrite URL with the keyword «redirect»:

This will result in a HTTP 302 Moved Temporarily redirect. In a browser, the URL in the address bar will change to the forwarded URL.

Permanent redirect (301 Moved Permanently)

The 302 status above is a helpful fix for a quick redirect — but not optimized for SEO. If you create a definitive redirect, you should set the permanent keyword at the end of the rewrite config:

Using last or break as keyword

Let’s try this without a redirect or permanent option but with break or last:

Internal address rewrite (without redirect)

So if you want to keep your requested URL in the browser address bar and simply want to rewrite the URL (same as with mod_rewrite in an Apache web server), you must use a relative path:

This will load the website for www.example.com from the subfolder /mypage within the document root (/var/www/www.example.com).

Internal address rewrite as reverse proxy

First everything (location /) is passed to tomcat (the defined upstream server). Then the redirect for the root path (/) is happening and is relative to the path.
This results in keeping the browser’s address URL at www.example.com but loads the website from 127.0.0.1:8080/mypage.

Internal address rewrite with dynamic path

Sometimes you may want to change the internal path, but still use (some parts of) the requested URI. You can use this by creating a selection using parentheses «()» and then refer to the selection with $1 for the first selection, $2 for the second selection and so on.

How to verify the internal URI rewrite

You can see these headers when using curl and looking at the response headers:

$ curl http://www.example.com/hello-my-world -IHTTP/1.1 200 OKServer: nginxDate: Mon, 21 Feb 2022 13:00:36 GMTContent-Type: text/htmlContent-Length: 162Connection: keep-aliveRequested-URI: /hello-my-worldFinal-URI: /mypage/hello-my-world

Add a comment

Show form to leave a comment

Comments (newest first)

Claudio Kuenzler from Switzerland wrote on Jan 25th, 2021:

Markus, no, including a proxy settings file is not required. However you might want to use some proxy settings such as X-Forwarded-Proto or X-Forwarded-For headers. You can of course also write these settings (using proxy_set_header) or other settings (such as proxy_redirect) directly in the location context.

Markus Kugler from wrote on Jan 24th, 2021:

Thanks Claudio Kuenzler!

what is proxy-settings.conf for? Do I need it?

Claudio Kuenzler from Switzerland wrote on Jan 23rd, 2021:

Hi Markus! In this case you should redirect your root location to «/this/is/important/» and the path «/this/is/important/» is proxying to the external domain.

Markus from wrote on Jan 22nd, 2021:

Hi *
great tutorial thanks!
What if I want to rewrite from https://sub1.domain.com/ to physically https://some-other-domain.com/this/is/important/link.html but the browser should show https://sub1.domain.com/this/is/important/link.html
in other words some-other-domain.com needs to be hidden from the public AND url should be redirected from / to /this/is/important/link.html

ck from St. Gallen, Switzerland wrote on Apr 8th, 2015:

U-lis from wrote on Mar 27th, 2015:

Hello, I have a question!

I tried your last server config to show example.com on address bar and load page from 127.0.0.1:8000/mypage.

Читайте также:  Clonezilla аналоги

But I got example.com/mypage on my addressbar with correct page I wanted.

Is Nginx config changed or my mistake?

I need your help. Thanks for your article.

Довольно часто при обращении к сайту используются редиректы на уровне вебсервера Nginx. Чаще всего редиректы применяют для изменения имени домена (без www на домен с www) или протокола (с HTTP на HTTPS).

Настройку на редиректов в NGINX можно сделать двумя способами — давайте разберемся!

Пример настройки редиректа с домена без www на домен с www:

# Вариант 1
return 301 $scheme://www.$host$request_uri;

# Вариант 2
rewrite ^ http://www.$host$request_uri? permanent;

Пример редиректа с HTTP на HTTPS:

# Вариант 1
return 301 https://$server_name$request_uri;

# Вариант 2
rewrite ^ https://$server_name$request_uri? permanent;

Рассмотрим подробнее вариант с использованием директивы rewrite:

Флаги могут принимать следующие значения:

  • permanent — редирект с кодом 301.
  • redirect — редирект с кодом 302.

В вариант с использованием директивы return:

коды могут использоваться любые, но чаще всего — 301, 302, 404.

Для обычного посетителя сайта разницы между кодами 301 и 302 нет. А вот для поискового робота разница огромная — 301-й редирект говорит о «склеивании» страниц. Это означает для поисковика то, что старая и новая страницы — это одно и тоже. Таким образом результаты ранжирования необходимо сохранить для новой страницы. 302-й редирект просто говорит о том, что нужно перейти по другому адресу. Поисковый робот не сохраняет результат выдачи для новой страницы, индексируя его с нуля.

Ключевые особенности обоих вариантов:

Introduction

HTTP redirection, or URL redirection, is a technique of pointing one domain or address to another. There are many uses for redirection, and a few different kinds of redirection to consider. Redirects are used whenever a site needs people requesting one address to be directed to another address.

Step 1 – Reviewing Redirect Methods

There are many use cases for redirects. If you have established a web presence and would like to change your domain, it is best not to just abandon your old domain. Bookmarks to your site and links to your site located on other pages throughout the internet will break if your content disappears without any instructions to the browser about how to find its new location. Changing domains without redirecting will cause your site to lose traffic from previous visitors and lose all of the credibility you have worked to establish.

Temporary Redirects

Temporary redirects are useful if your web content for a certain URL temporarily needs to be served out of a different location. For example, if you are performing site maintenance, you may need to use a temporary redirect of all of the pages for your domain to an explanation page to inform your visitors that you will be back shortly.

Temporary redirects inform the browser that the content is temporarily located at a different location, but that they should continue to attempt to access the original URL.

Permanent Redirects

Permanent redirects are useful when your content has been moved to a new location forever.

This is useful for when you need to change domains or when the URL needs to change for other reasons and the old location will no longer be used. This redirect informs the browser that it should no longer request the old URL and should update its information to point to the new URL.

Forcing SSL

A common use for redirects is directing all site traffic to use SSL instead of standard HTTP.

Using redirects, it is possible to make all requests for http://www.mysite.com be redirected to https://www.mysite.com. Using LetsEncrypt to provide HTTPS will automatically generate a redirect configuration like this.

In the next part of this tutorial, you will learn some example configurations for redirects using the Apache web server. If you are using Nginx instead and you have no plans to use Apache, you can skip to Step 3.

Step 2 – How to Redirect in Apache

Apache can redirect using a few different tools. Straightforward redirects can be implemented with tools from the mod_alias module, and more extensive redirects can be created with mod_rewrite.

Читайте также:  Учет создания интернет-сайта

Using the Redirect Directive

In Apache, you can implement single-page redirects using the “Redirect” directive, which is included in the mod_alias module that is enabled by default. This directive takes at least two arguments: the old URL and the new URL.

You can open that configuration using nano or your favorite text editor:

By default, it contains a standard web server configuration that will listen on port 80 and look for an index.html file located in /var/www/html on your system.

Save and close the file. If you are using nano, press “Ctrl+X”, then when prompted, “Y” and then Enter.

This redirect instructs the browser to direct all requests for www.domain1.com to www.domain2.com. This is only for a single page, not for the entire site.

Using the RedirectMatch Directive

To redirect more than a single page, you can use the RedirectMatch directive, which allows you to specify directory matching patterns using regular expressions.

This will allow you to redirect entire directories instead of just single files.

RedirectMatch matches patterns in parenthesis and then references the matched text in the redirect using “$1”, where 1 is the first group of text. Subsequent groups are given numbers sequentially.

As with the Redirect directive, you can specify the type of redirect by adding the redirect code before the URL location rules.

In order for your changes to take effect, you’ll need to restart Apache. On a modern Ubuntu server, you can do this using systemctl:

systemctl restart apache2

Using mod_rewrite to Redirect

The most flexible, but complicated way to create redirect rules is with the module called mod_rewrite. For information on working with mod_rewrite, refer to How to Rewrite URLs with mod_rewrite for Apache.

Step 3 – How to Redirect in Nginx

The return directive executes a URL substitution and then returns the status code given to it and the redirection URL.

In this case, it uses the $scheme variable to use whatever scheme was used in the original request (http or https). It then returns the 301 permanent redirect code and the newly formed URL.

For a permanent redirect, you could change redirect to permanent at the end of the statement.

In order for your changes to take effect, you’ll need to restart Nginx. On a modern Ubuntu server, you can do this using systemctl:

systemctl restart nginx

You can expand on this configuration in many other ways. Using these fundamentals of Nginx in order to produce your desired server configuration can keep your stack very lean, as well as helping to concisely document and handle any potential edge cases around your server traffic.

Conclusion

In this tutorial, you learned to configure both temporary and permanent redirects for popular web servers. Be sure to use the correct redirection type, as an improper use of temporary redirects can hurt your search ranking.

HTTP redirection is way to point one domain or address to another. There are a few different kinds of redirects, each of which mean something different to the client browser. The two most common types are temporary redirects and permanent redirects.

Temporary redirects (response status code 302 Found) are useful if a URL temporarily needs to be served from a different location. For example, if you are performing site maintenance, you may wish to use a temporary redirect from your domain to an explanation page to inform your visitors that you will be back shortly.

Permanent redirects (response status code 301 Moved Permanently), on the other hand, inform the browser that it should forget the old address completely and not attempt to access it anymore. These are useful when your content has been permanently moved to a new location, such as when you change domain names.

This guide will cover a more in depth explanation of how to implement each kind of redirect in Nginx, and go through some examples for specific use cases.

Читайте также:  Раскрытие возможностей PHPMyAdmin: как легко создавать запросы

Prerequisites

In Nginx, you can accomplish most redirects with the built-in rewrite directive. This directive is available by default on a fresh Nginx installation and can be used to create both temporary and permanent redirects. In its simplest form, it takes at least two arguments: the old URL and the new URL.

Temporary redirect with rewrite

. . .

^/$ http://www.domain2.com redirect
. . .

This redirect instructs the browser to direct all requests for www.domain1.com to www.domain2.com. This solution, however, works only for a single page, not for the entire site. To redirect more than a single page, you can use the rewrite directive with regular expressions to specify entire directories instead of just single files.

redirect matches regular expression patterns in parenthesis. It then references the matched text in the redirect destination using $1 expression, where 1 is the first group of matched text. In more complex examples, subsequent matched groups are given numbers sequentially.

. . .

^/(.*)$ http://www.domain2.com/ redirect
. . .

. . .

. . .

By default, the rewrite directive establishes a temporary redirect. If you would like to create a permanent redirect, you can do so by replacing redirect with permanent at the end of the directive, like this:

^/$ http://www.domain2.com permanent
^/(.*)$ http://www.domain2.com/ permanent

Let’s move on to some specific examples.

Example 1 — Moving to a Different Domain

If you have established a web presence and would like to change your domain to a new address, it is best not to just abandon your old domain. Bookmarks to your site and links to your site located on other pages throughout the internet will break if your content disappears without any instructions to the browser about how to find its new location. Changing domains without redirecting will cause your site to lose traffic from previous visitors and older links.

In this example, we will configure a redirect from the old domain called domain1.com to the new one called domain2.com. We’ll use permanent redirects here because the old domain will be deprecated, and all traffic should go to the new domain from now on.

We’ll also assume you are already serving your future version of website at domain2.com:

. . .

^/(.*)$ http://domain2.com/ permanent
. . .

We’ve added the aforementioned redirect using a rewrite directive. The ^/(.*)$ regular expression matches everything after the / in the URL. For example, http://domain1.com/index.html will get redirected to http://domain2.com/index.html. To achieve the permanent redirect we simply add permanent after the rewrite directive.

Note: Remember to test your configuration using nginx -t and then restart Nginx after you make your changes.

Example 2 — Creating a Persistent Experience Despite Single Page Name Changes

Let’s assume your website had two separate pages for products and services called products.html and services.html respectively. Now, you’ve decided to replace those two pages with a single offer page called offers.html instead. We will configure a simple redirect for products.html and services.html to offers.html.

. . .
example.com www.example.com
. . .

Configuring the redirects is as simple as using two redirect directives.

Redirects added to the original configuration

. . .
example.com www.example.com

^/products.html$ /offer.html permanent
^/services.html$ /offer.html permanent
. . .

The rewrite directive accepts the original address that has to be redirected as well as the destination address of a new page. Since the change here is not a temporary one, we used permanent in the directive as well. You can use as many redirects like this as you wish to make sure your visitors won’t see unnecessary 404 Not Found errors when moving site contents.

You now have the knowledge to redirect requests to new locations. Be sure to use the correct redirection type, as an improper use of temporary redirects can hurt your search ranking.

There are multiple other uses of HTTP redirects, including forcing secure SSL connections (i.e. using https instead of http) and making sure all visitors will end up only on the www. prefixed address of the website.

Оцените статью
Хостинги