Score:1

Nginx Redirection Rule

bo flag

I am trying to redirect

  • https://example.com/1001/def.txt -> https://example.com/1001/1/def.txt
  • https://example.com/1001/* -> https://example.com/1001/1/*
location /2023/ {
  if ($request_uri ~* "/2023/(.*)") {
    return 302 /1/$2 break;
  }
}

The problem I am facing is that, whenever I am trying to match the path /1001/ and redirect it to the destination path, that also contains 1001 in /1001/1/, the request goes into an infinite loop.

Zareh Kasparian avatar
us flag
are you sure the location specified in the configuration is correct? you have 2023 while in the example you have 1001
Score:1
br flag

To prevent infinite loop, you need to use a rewrite condition that only matches the original URL and not the rewritten one. You can achieve the desired redirection using the following nginx configuration:

server {
    listen 80;
    server_name example.com;
    location /1001/ {
        if ($request_uri !~ "^/1001/1/") {
            rewrite ^/1001/(.*)$ /1001/1/$1 permanent;
        }
        # Your other server configuration
    }
}

This configuration uses the if directive to add a condition that the URL should not contain /1001/1/. The rewrite directive is then used to redirect requests to /1001/ to /1001/1/. The $1 in the destination URL captures the portion of the URL that matched the (.*) pattern. The permanent flag indicates that this should be a permanent redirect.

sv flag
Beautiful answer. Simple too. I was wondering for an (easy) answer for a similar question posted recently... https://serverfault.com/q/1122268/102173
Score:0
us flag

You can try following setup:

location ~ ^/1001/[1-9]/ {
    # block configuration
}

location ~ ^/1001/(.*) {
    return 302 /1001/1/$1;
}

The order of location blocks is significant: nginx uses the first matching regular expression location for processing the request. You can adjust the regular expression in first location block to more accurately match your desired target URL structure.

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.