9

I'm making redirects of products from old to new category.

I've managed to make it work with following rule:

rewrite ^/old-category/(.*) /new-category/$1;

But I want to know when should I use "end line" sign $ and what's the difference with it or without it in my case. For example:

rewrite ^/old-category/(.*)$ /new-category/$1;

Also I want to redirect users if they simply write old category name (without products), should I create a new rule just for category redirect or I can edit the current rule above to work in both cases.

Thank you for your answers in advance.

9

Answering your questions in order...

This

rewrite ^/old-category/(.*) /new-category/$1;

and this

rewrite ^/old-category/(.*)$ /new-category/$1;

as written are equivalent. The .* rule matches 0 or more of "everything", so the $ is redundant/not really needed.

The $ terminator is useful when you want to match strings that end in a specific way, for example

rewrite ^/old-category/(.*)\.php$ /new-category/$1;

to rewrite only PHP files.

As for your second question, if I understood correctly, you want to redirect this

http://example.com/old-category/

to this

http://example.com/new-category/

If that's so, it's already done by the rewrite rule, as .* matches ZERO or more characters.

  • 3
    Good question, good answer. So many people set the $ by default (or leave it out by default) without thinking about what it actually means. Every time I see (.*)$ I cringe. I didn't try it but it might actually be that leaving out the $ in this case could have a slightly better performance as it's another rule regex has to check for. Would be interesting to get an answer to that question :D – Broco Oct 8 '18 at 11:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.