Rewrite Rules in Nginx
Tags: nginx, webdev, devops
Published: 2021-10-21 10:31:14

---
title: Rewrite Rules in Nginx
published: true
description: Return directive and Rewrite directive - two widely used methods for rewriting the URLs, rewrite directive is more powerful. Read the post to learn why and how to rewrite.
tags: Nginx, webdev, devops
canonical_url: https://blog.engineyard.com/rewrite-rules-nginx?utm_source=dev.to&utm_id=QiWorks.in
//cover_image: https://blog.engineyard.com/hubfs/Blog%20_Nginx%20%281%29.jpg
---
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bquiwx7lg56c0w0hj5n6.jpg)
By [Ritu Chaturvedi](https://blog.engineyard.com/author/ritu-chaturvedi)

_Rewrite rules_ modify a part or whole of the URL. This is done for two reasons. First, to inform clients about the relocation of resources, and second, to control the flow to Nginx. The two general-purpose methods used widely for rewriting URLs are the _return_ directive and the _rewrite_ directive. Of these, the rewrite directive is more powerful. Let's discuss why it is so, as well as how to rewrite the URLs.

Having a better [understanding of NGINX](https://www.thegeekstuff.com/2013/11/nginx-vs-apache/) will make it easier to follow this blog.

**_Return_**  **directive**

_Return_ is the easiest way to rewrite a URL declared in the server or local machine.

**_Return_**  **in Server:**

Suppose your site is migrated to a new domain and all existing URLs are to be redirected here; run the below code to direct any new request to your site.

![Return in Server - Rewrite rule in Ngnix](https://blog.engineyard.com/hs-fs/hubfs/image1-3.png?width=620&name=image1-3.png)

This directs all requests that hit _www_._previousdomain_._com_ to _www_._currentdomain_._com._ The _www_._previousomain_._com_ will send out a '301' error as soon as the above code is run, and a new access request is generated. The two variables, _$scheme_, and _$request\_uri,_ get data from the input URL. '_Listen 80'_ indicates that the block applies to both HTTP and HTTPS requests.

**_Return_**  **in local**

If you want to redirect pages in place of a complete domain, you can use the _return_ directive under the location block.

Knowing [how to create the Nginx rewrite](https://www.nginx.com/blog/creating-nginx-rewrite-rules/) rules can save a lot of your effort and time.

**Rewrite directive**

Just like the _return_ directive, the rewrite directive can also act in both server and local. Compared to the _return_ directive, the _rewrite_ directive can handle complex replacements of URLs. The following is the syntax of the _rewrite_:

![rewrite directive - Rewrite rule in Ngnix](https://blog.engineyard.com/hs-fs/hubfs/image3-2.png?width=627&name=image3-2.png)

The _regex_ is a regular expression that matches against incoming URI.

The _replacement\_url_ is the string used to change the requested URI.

The value of the _flag_ decides if any more redirection or processing is necessary.

**Static page**  **_rewrite_**

Suppose you want to redirect the page _https_://_example_._com/tutorial_ to _https_://_example_._com/new\_page_. The directive will be:

![static page rewrite - Rewrite rule in Ngnix](https://blog.engineyard.com/hs-fs/hubfs/image2-3.png?width=622&name=image2-3.png)

The line _location = /tutorial_ defines that any identification of the tutorial is to be replaced. The _rewrite_ command says to replace the phrase within notations _^_ and $ with '_new\_page.html'_ and then break the command. The notation '?' is termed as a non-greedy modifier, after which the pattern search is stopped.

**Dynamic page**  **_rewrite_**

Consider rewriting the URL _https_://_www_._sample_._com/user.php?id=11_ to _https_://_www_._sample_._com/user/11_. Here, the user=11 is to be replaced. By using the static rewrite method, it would require writing the rewrite command 10 times. Instead, let's do it in a single go.

![dynamic page rewrite - Rewrite rule in Ngnix](https://blog.engineyard.com/hs-fs/hubfs/image4-3.png?width=622&name=image4-3.png)

The line _location = /user.php_ asks Nginx to check for the prefix'/user'. As said earlier, the Nginx will search for phrases between the start and end notations as _^_ &nbsp;and $ along with the non-greedy '?' modifier. The phrase in our example is a range of users. It is mentioned inside the square brackets as [0-9]+. The back-reference in this expression is noted within the parenthesis and is referred to by the $1 symbol. So, for our example, the rewrite will happen for all users automatically.&nbsp;

One special case under the dynamic reference is the multiple back-references.&nbsp;

Now, we have discussed how to write the rewrite rules for simple and complex URLs.

Understand the detailed working of rewrite rules through some [examples](https://www.thegeekstuff.com/2017/08/nginx-rewrite-examples/) handling various scenarios.

## **Directive Comparison**

Let's analyze both directives by comparing them and find out why the rewrite derivative is more powerful.

**Return directive**

- It is simple to use and understand.&nbsp;
- It can be used in both server and location contexts.&nbsp;
- It explicitly mentions the corrected or updated URL so that the client can use them in the future.&nbsp;
- Return directives can include multiple error codes as well.
- For codes 301, 302, 303, and 307, the URL parameters define the redirect URL.&nbsp;

_return (301 | 302 | 303 | 307) url;_

- For other codes, the text is to be explicitly mentioned by the user.&nbsp;

_return (1xx | 2xx | 4xx | 5xx) ["text"];_

For example: _return 401 "Access denied because the token is expired or invalid";_

- This directive can be used in scenarios where the return URL is correct for both server and location block, and rewritten URL is built with Nginx variables.

**Rewrite directive**

- It can accommodate more complex URL modifications where capturing elements without Nginx variables or an update in the elements in the path is required.
- It can be used in both server and location contexts.&nbsp;
- The rewrite directive can return only code 301 or 302. To accommodate other codes, explicitly add the return directive after the rewrite directive.
- It may not send the redirect details to the client.
- The Nginx request processing is not halted.

## **Conclusion**

The _return_ and _rewrite_ directives can be used to redirect URLs in both server and location contexts. Though the return directive is much simpler, the rewrite directive is widely used as it can also handle complex modifications/updates to the URLs.