In this article we’ll present the Nginx rules needed to internally rewrite URIs and equalize two or more URLs.

As an example, we’ll be requesting one URL but load different content for it. To do this, we’ll create a rule to catch the URI pattern and rewrite it to the default location so it can be processed accordingly.

Use Case

A common use case for internal rewriting is for ignoring dynamically generated parts of the URL – like some CMS’s use in the process of generating article URLs (Magento) – and for simplifying the storage system. (Note: URL reverse-rewrite is not needed in this case.)

Internal rewriting is also for when you want to have a multi-level URL structure but only use a single level storage structure without the URL rewrite process in place on the origin side.

Rule #1

Nginx Configuration Block

location ~ ^\/(one)(.*) {                          
		rewrite ^\/(one)(.*) /$2 last;
...
}

 

Visualization of Regex

 

Rule #2

Nginx Configuration Block

location / {
		proxy_set_header Host "domain.com";
		proxy_pass http://domain.com;
…
}

 

CURL Examples

NOTE: Showing the same response for two different URLs (/one/) doesn’t even exist in my test environment.
$ curl -I http://myzone.mycompany.netdna-cdn.com/one/
HTTP/1.1 200 OK
Date: Sat, 19 Sep 2015 21:44:36 GMT
Content-Type: text/html
Content-Length: 935
Connection: keep-alive
Last-Modified: Thu, 06 Aug 2015 12:32:59 GMT
Vary: User-Agent,Accept-Encoding
Server: NetDNA-cache/2.2
X-Cache: MISS
Accept-Ranges: bytes
$ curl -I http://myzone.mycompany.netdna-cdn.com/
HTTP/1.1 200 OK
Date: Sat, 19 Sep 2015 21:44:45 GMT
Content-Type: text/html
Content-Length: 935
Connection: keep-alive
Last-Modified: Thu, 06 Aug 2015 12:32:59 GMT
Server: NetDNA-cache/2.2
X-Cache: HIT
Accept-Ranges: bytes

 

If you have any questions, feel free to start a live chat or leave a comment below. You can also learn more about Nginx rules on MaxCDN One and NginxTips.com.