1

I'm new to nginx and I need to setup up a load of 301 redirects each pointing old files to the new ones, like this:

# www.domain.com/products/category/product.php?id=103 
# to 
# www.domain.com/products/new-category-name/new-product-name.html 

To deal with the ? I have the following which seems to be working fine:

if ($args ~ "id=103") {
    rewrite ^ /products/new-category-name/new-product-name.html? permanent;
}

How does this look? I'm aware that if is mostly a bad idea in nginx but I don't fully understand why. Is the above rule okay? it seems to work fine. Lastly, I have around 100 of these urls to redirect. Will it be okay to just duplicate this rule for each url?

Thanks


UPDATE
The mapping looks to be a great solution but I'm not sure where to place the code. I currently have the following:

location / {
    try_files $uri $uri/ @modx-rewrite;
}

It's stated that any additional rules need to be placed before this location block.

1 Answer 1

3

I would sugguest to use the ngx_http_map_module

create a file for the urlmapping, that contains old and new urls, like

/products/category/product.php?id=103    /products/new-category-name/new-product-name.html ;
/products/category2/product.php?id=104   /products/new-category2-name/new-product104-name.html ;

that's easy to maintain. just add a new line for a new mapping and reload your nginx config.

in your nginx config create a location with a mapping like

map $request_uri $newuri {
    include /path/to/your/mappingfile;
}
server {
    ...
    location / {
        if ($newuri) {
            return 301 $newuri;
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

That's a good idea, but the map directive will need to be outside of the server block.
This looks great but I'm not sure where to place it. I've updated my question with more information, thanks
Thanks so much @hzei unfortunately I don't have access to outside the server block so I can't use this solution. I've set it as the accepted answer though as it otherwise looks perfect. I'm open to other suggestions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.