Search code examples
nginxhttp-redirectreturnnginx-location

Problem redirecting (301) w/ Nginx directives from old site subdirectory & wildcard address/args to new webroot


I had two old subdirectories that a site used to be located under, that are now all contained within the webroot.

I need to redirect all old link traffic to new location with nginx directives.

For example:

  • https://www.example.com/s/<wildcard>?<args>
  • https://www.example.com/sc/<wildcard>?<args>

Needs to redirect to the same site minus the subdirectory:

  • https://www.example.com/<wildcard>?<args>

I've tried the following but it's only redirecting URL's without the wildcard and arguments. So this returns a 404:

  • https://www.example.com/sc/index.php?rn=123

but

  • https://www.example.com/sc (or /sc/)

is stripped of the subdirectory correctly.

The two directives I've come up with are:

location ~* ^/sc/(.*) {
   return 301 /$1;
}

location ~* ^/s/(.*) {
   return 301 /$1;
}

Thanks in advance for any suggestions!


Solution

  • The rewrite directive automatically handles arguments, and the location ^~ operator is unambiguous.

    For example:

    location ^~ /sc/ {
        rewrite ^/sc(.*)$ $1 permanent;
    }
    location ^~ /s/ {
        rewrite ^/s(.*)$ $1 permanent;
    }