1

I have www.example.com/test and i want to write a condition if requested url is not equal to /test do a rewrite or redirect to www.example.com. The closest i can get is a code below but when i want to use www.example.com/test without / at the end it redirects me to www.example.com but when i type www.example.com/test/ it works.

location / 
fastcgi_param  REQUEST_URI $request_uri;
fastcgi_param  HTTPS on;

if ($request_uri !~ ^/test/(.*)$)
{return 301 $scheme://www.example.com;}

   try_files $uri $uri/ /index.php$is_args$args;
}
justdoole
  • 11
  • 1
  • 1
  • 2

1 Answers1

1

Nginx If

Generally with Nginx you avoid using the IF statement. It takes more resources and doesn't always work how you want.

Solution

The way you do this is to define two locations, catchall and test.

# I just copied this from above, you might want it in a block
fastcgi_param  REQUEST_URI $request_uri;
fastcgi_param  HTTPS on;

# Return permanent redirect for everything other than the /test URL
# Suggest you use 302 until you have this working perfectly. Google / browsers
# caches 301 redirects for a long time
location / {
  return 301 $scheme://www.example.com;
}

location /test {
 try_files $uri $uri/ /index.php$is_args$args;
}

I think this will work for both /test and /test/ . If not you could try this, which might work

location ~* /test

You should read up on how Nginx works, particularly location block matching. I think this article is likely to be useful.

Tim
  • 30,383
  • 6
  • 47
  • 77