dallen
dallen

Reputation: 2651

nginx redirect ignoring slash

I have some URLs that looks like this:

http://www.mywebsite.com/stuff/web-design-development

http://www.mywebsite.com/web-design/

http://www.mywebsite.com/web-design/secondary-page

Basically, I need anything from /web-design, with or without slash, and including anything after a slash (like the third URL) redirected to /. But the problem I'm having is that my redirect affects the first URL, because it has "web-design" in it.

Here's what I have:

if ($request_filename ~ web-design/.+) {
    rewrite ^(.*) http://www.mywebsite.com permanent;
}

Any idea how I can correct this?

Upvotes: 0

Views: 308

Answers (2)

dallen
dallen

Reputation: 2651

I was able to solve this by simplifing my rewrites.

Instead of using if statements, I just did:

rewrite ^/web-design/?$ http://www.mywebsite.com/ permanent;

Upvotes: 0

Mohammad AbuShady
Mohammad AbuShady

Reputation: 42799

A simple location block will match all these

location /web-design {
  return 301 $scheme://www.mywebsite.com;
end

This will match any thing that starts with /web-design and redirect it.

Here's why return and not rewrite and here's the location directive documentation.

Also keep in mind that 301 responses are cachable, if you are experiencing weird behaviour consider clearing your cache because maybe your browser cached an old 301 when the configuration wasn't correct yet.

Upvotes: 1

Related Questions