Score:0

How to redirect URLs containing random string in Nginx

cn flag

In my access log I've got random a lot of query strings, it is something like this

    https://example.com/?rJWLuVR1=JXhedT2G
    https://example.com/?JuntjUsc=kfLAIJCx
    https://example.com/?c6wx3Tk4=aXDtGrKd
    https://example.com/?UEEwPi5r=q48ugHy0
    https://example.com/?HWDtubBC=TC4utO9p
    https://example.com/?Gqs8KzOp=klbC9t48
    https://example.com/?tTKR1vY0=knRAYtuG
    https://example.com/?jn2UFqCY=Ar08xrlr
    https://example.com/?pXmuazUj=CMTXGmhq
    https://example.com/?t443qiT7=VbXbxXuQ
    https://example.com/?aTScktcA=foaOJaVt
    https://example.com/?qbWcbdbu=CQgmMCQL
    https://example.com/?xUeZFI5s=8GEoS7jv
    https://example.com/?eS5viG89=aF59lpye

Etc...

  • There is no specific pattern after question mark "?"

  • There are 17 characters including "=" on the 9th

I'd like to redirect those URLs to homepage.

This is what I've done so far but it didn't work well.

location / {
    if ($args = "=") {
        return 301 https://example.com/;
    }
}

What am I supposed to do?

Regards

Score:0
jp flag

Yes, you can redirect URLs with these conditions using a regular expression in the if statement.

Here is an example of how you can do it:

server {
    listen 80;
    server_name example.com;

    location / {
        if ($args ~ "^.{8}=.{8}$") {
            return 301 /;
        }
    }
}

This if statement uses a regular expression to match any URL with 17 characters after the ? including an = on the 9th character. The regular expression "^.{8}=.{8}$" means:

  • ^ Start of the string
  • .{8} Any 8 characters
  • = A literal = character
  • .{8} Any 8 characters
  • $ End of the string

This configuration will redirect any URL with this pattern to the home page.

Note that this configuration will only work if the URL has no other query parameters. If the URL has other query parameters, you will need to modify the regular expression to take them into account.

user3195859 avatar
cn flag
It works! Thank you very much.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.