How to Get Last Part of URL in NGINX


get last part of url in nginx

Sometimes, you might need to extract the last part of URL to process it further. For example, you might want to redirect users based on its value or display a custom message. NGINX makes it easy to accomplish this with just 1 line of code. Let us take a look at how to get last part of URL in NGINX.

 

How to Get Last Part of URL in NGINX

Here are the steps to get last part of URL in NGINX.

 

1. Open NGINX config file

Open NGINX config file in a text editor.

You will find it at one of the following locations, depending on the type of installation


/etc/nginx/conf.d/default.conf
/etc/nginx/sites-enabled/default
/etc/nginx/nginx.conf

 


$ sudo vim /etc/nginx/nginx.conf

 

 

2. Get last part of URL

We will use the environment variable $request_uri to extract last part. In your server, location block, add the following lines of code.

if ($request_uri ~* "([^/]*$)" ) {
  set  $last_part  $1;
}

The above code will parse the requested URL and store $1, that is, last of URL in $last_part variable. Once you have set the variable, you can use it in further location blocks for processing.

Here’s an example, of its use in location block

 


location / {
 if ($request_uri ~* "([^/]*$)" ) {
  set $last_part $1;
 }
 if ($last_part ~* "product" ) {
  return 301 /new-product;
 }
 ...#configuration
}

 

3. Reload NGINX web server

Test the config file to ensure there are no errors.

$ sudo nginx -t

 

If you get no error message, reload NGINX server to apply changes.

$ sudo service nginx reload

 

 

About Sreeram Sreenivasan

Sreeram Sreenivasan is the Founder of Ubiq, a business dashboard & reporting platform for small & medium businesses. Ubiq makes it easy to build business dashboards & reports for your business. Try it for free today!