How remove two specific param from url NGIX

Posted October 5, 2017 1.2k views

Hello, i have this url and want remove the “-2” from second parameter in the url and that it stays that way, The “-2” is random. i don’t have idea how to do it :( any help would appreciate it.

My apologies for my bad english

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.

Submit an Answer
1 answer

This can be accomplished using an Nginx rewrite rule. These use regular expressions to match different parts of the URL and then “rewite” them.

There will be differences based on whether xxxx is alaways xxxx or if you also want yyyy to match, but here is a minimal working example as a reference point:

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /var/www/html/;
    index index.html index.htm;

    rewrite (xxxx/.*)-\d+(.*)$ /$1$2 last;

Breaking down the regex a bit:

  • (xxxx/.*) captures every thing highlighted in red: xxxx/xx-xx-2/xxxx
  • -\d+ matches on: xxxx/xx-xx-2/xxxx
  • (.*)$ captures every thing that follows: xxxx/xx-xx-2/xxxx

Then /$1$2 takes the first captured part ($1) and appends the second ($2), leaving you with: xxxx/xx-xx/xxxx is a great tool for testing and explaining how different regular expressions work.
Check out this one, and modify it as needed for your real use case:

by Shantanu Kulkarni
This tutorial will give an insight to regular expressions without going into particularities of any language. We will simply use egrep to explain the concepts. Regular expressions are templates to match patterns (or sometimes not to match patterns). They provide a way to describe and parse text.