nginxnginx-confignginx-location

Accessing just a specific folder should redirect


I would like to be able to redirect users who visit a folder/directory in my nginx website I do not intend on people actually viewing. Example: if a client accessed a directory like https://example.com/_/ or https://example.com/_ they would be redirected to https://example.com/, but only if they haven't accessed anything inside that directory. For example, they shouldn't be redirected if they accessed a resource or another directory within that directory like https://example.com/_/image.jpg or https://example.com/_/fonts/.

I already have a plain ol HTML file which redirects but I find that crude and I want to replace it with a better solution. I tried setting up a location but I couldn't figure out how to make it not rewrite if its not just /_/ or /_. Here is the latest attempt (it didn't work):

location /_ {
    rewrite ^/_(?/)(!.*)$ https://example.com/ redirect;
}

I'm fairly new to Nginx and hosting websites so pardon me if I missed a very simple solution.


Solution

  • You want to redirect two URLs, /_ and /_/. But not anything else, like / and /_/foo, etc.

    The location /_ rule matches any URL that begins with /_, so is not what you need.

    The location = /_ rule matches a single URL.

    So you could add two of these types of rule to redirect to https://example.com/.

    For example:

    location = /_ { return 301 /; }
    location = /_/ { return 301 /; }
    

    Note that Nginx will automatically add the scheme and hostname from the original request.