Nginx redirect rule




I have links as below:

I want to redirect 3rd url only.
Can someone give a NGINX url to redirect third url.
In third url I will need to take NUMBER and redirect to:

@orng @itsbhanusharma


Sorry for the delayed response, I’ll share the exact rule with you tomorrow.

Just a question:
You need it pure nginx or some alternative language code will work too? E.g. a php bridge to perform the task?


Need pure nginx
Any update @itsbhanusharma


Give this a shot?

location ~ ^/test-cat/.+-ABC-([0-9]+)\$ {
    return 301$1;

warning This is not tested


I am trying to redirect 3rd link in my example.


Updated to match directory


Sorry to bother again but I never understood this concept.
How it works.

Below url I need to redirect.


Now As I understand with your example, you have redirected last whole thing or only NUMBER that you will be taking out?

location ~ ^/test-cat/.+-ABC-([0-9]+)\$ {
    return 301$1;

Here what does 1 means?


$1 will be the condition that we specified above!
Reducing the directory and taking everything between 0-9 present in the url!
I’ve made up this fragment so I’m not really sure if it will work though.

An easier approach will be to pass all the urls through a validation and pick up the numeric ID in the process. Then using that ID to construct the url.


Tough to understand this point :frowning:
Thanks for quick response.


Ok let me try to break this down!

In your favourite programming language, create a small logic that reads the requested url with a regex:
var id = url.match([0-9]+)
then set a url constructor

this code can be refined but in a perfect world, it should store the requested url’s numeric part into the variable id and then pass it on to the return statement.


That was my original idea but thought why to put extra load on application server, if NGINX can handle itself.


Nginx or apache2 or any other webserver isn’t smart enough to do it and it won’t really add any additional load. Maybe @itsbhanusharma has a better theory about it but we haven’t noticed any significant load.

However, your point makes me wonder that you can make the same logic in nginx config too.


Being honest, I’ve never personally tried it so I’m also shooting the bullet in the dark but it should be fairly simple regex to strip out the numbers from a url but I’ve yet to find a working logic for the same.


I found this topic on serverfault and it seems like extraction is possible but needs some refining!

The big problem in your case is that the ID is a part of the url if it was a separate identifier then it may have made things easier.

I.e. if the url was like:

Then it would have made life easier

Location ^/*/*