Report this

What is the reason for this report?

Is this the proper way to use an NGINX rewrite to strip a subdirectory off a request?

Posted on February 16, 2021

I’m using a location block to respond to requests at http://domain.com/v3/ but I want requests for resources like /v3/accounts/ to be passed to the application as simply /accounts/.

I’ve configured the following rewrite rule in the location block, but I was reading about taxing rewrites in the NGINX docs and I was hoping somebody could tell me if I’ve written the wrong type of regex for this rewrite:

 rewrite ^/v3/(.*)$ /$1 break;

Thank you!



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Heya,

Just came across this answer and decided to write some general guidelines for anyone who comes across this in the future despite the old question.

The rewrite rule you’ve shared rewrite ^/v3/(.*)$ /$1 break; looks correct for your requirements. This rule essentially strips the /v3 part from the beginning of the requested URL.

The ^/v3/(.*)$ part of the rule is a regular expression that matches any URL that starts with /v3/. The .* matches any character in the URL after /v3/. Combined, they match /v3/ followed by anything.

The /$1 part of the rule is where matched URLs get rewritten to. $1 is a special variable that contains the value matched by the .* in the regular expression.

The word break at the end of the rule stops processing further rewrite rules if this one matches.

Hope that this helps!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.