MostXlent1
MostXlent1

Reputation: 123

Nginx Config, Deny Image Stored in Specific Folder If $http_cookie Isn't Set

I am currently launching a WordPress site that moves image uploads into a certain folder when they are added. On my development server I have made it so that images stored in this folder are NOT ACCESSIBLE, unless a specific $http_cookie is set in the browser. Here is the location block I'm using for this in my development NGINX config:

location ~ ^/wp-content/uploads/employee_message/(.*) {
        if ($http_cookie !~ 'wp_2651267=user_employee123') {
                return 301 https://sitename.com;
        }
}

On the development server, when I view a file such as http://sitename.com/wp-content/uploads/employee_message/1234-5678-1234-5678/image_here.png for example, it will only allow me to view that if the I have the wp_2651267=user_employee123 cookie set. This is good.

However, when I move this location block into my production config (I'm using RunCloud) it allows the image to be viewed with or without the cookie. This is no good.

I'm seeing that this location block below is part of the default config, and my block above gets pulled in AFTER this one:

location ~ .(ico|css|gif|jpe?g|png|gz|zip|flv|rar|wmv|avi|css|js|swf|png|htc|mpeg|mpg|txt|otf|ttf|eot|woff|woff2|svg|webp)$ {
    expires     1M;
    include /etc/nginx-rc/conf.d/sitename.d/headers.conf;
    add_header  Cache-Control "public";
    include /etc/nginx-rc/extra.d/sitename.location.static.*.conf;
    try_files $uri $uri/ /index.php$is_args$args;
}

Is it possible that this is undoing the cookie business I'm adding in?

Here is an example config that RunCloud uses: RunCloud NGINX Config

My location block gets pulled in on this line:

include /etc/nginx-rc/extra.d/runcloud-blog.location.main.*.conf;

There are no errors when I run a test, and it has definitely been reloaded many, many times. Are there any reasons that my location block isn't working in this setup? Is there more information I can provide to help troubleshoot this?

Thanks so much for taking the time to read this! Please let me know if you have any insights.

Thanks, -Ryan

Upvotes: 0

Views: 347

Answers (1)

Shawn C.
Shawn C.

Reputation: 6841

To help people that find this question in future

Nginx then tries to match against the regular expression locations sequentially. The first regular expression location that matches the request URI is immediately selected to serve the request.

via Understanding Nginx Server and Location Block Selection Algorithms

Per the question, the less restrictive regex location was declared BEFORE the more restrictive location so it was selected as the location to serve the request.

By moving the more restrictive location BEFORE the other will cause it to be selected when the regex matches.

Upvotes: 1

Related Questions