NGNIX - Rewrites

less than 1 minute read

The rewrite directive:

Changes part or all of the URL in a client request:

  • To inform clients that the resource they’re requesting now resides at a different location
  • To control the flow of processing within NGINX:
    • Example: To forward requests to an application server when content needs to be generated dynamically

Sample Rewrites

rewrite ^(/download/.*)/media/(\w+)\.?.*$ $1/mp3/$2.mp3 last;
rewrite ^(/download/.*)/audio/(\w+)\.?.*$ $1/mp3/$2.ra  last;
return  403;
location /download/ {
    rewrite ^(/download/.*)/media/(.*)\..*$ $1/mp3/$2.mp3 break;
    rewrite ^(/download/.*)/audio/(.*)\..*$ $1/mp3/$2.ra  break;
    return  403;
}

Example of the rewrite directive, used inside a location directive that uses an external URL:

location /downloads {
        rewrite ^(/downloads)/(.*)$ http://downloads.testdomain.local:9084/$2 permanent;
        return 403;
}

This rewrite grabs the file name after /downloads and sends the request to the URL: http://downloads.testdomain.local:9084/filename

Categories:

Updated: