V
V
Valery Correspondence2014-10-25 21:20:41
Nginx
Valery Correspondence, 2014-10-25 21:20:41

How to form correct regexp for nginx location ?

Hello!
Please help me set up nginx in a certain way. Nginx is in front of Apache. The application stores cached files in the site folder - /home/admin/web/site.ru/public_html/cache.
It is necessary for a request like " site.ru/12345/any-text " in the absence of a cookie "cookie_name" to check for the presence of the file /home/admin/web/site.ru/public_html/cache/12345 and return it. And also use compression for this file, if possible, and specify the header data type - html. If not, send a request to Apache.
I try like this:

server {
    ...
    location ~/test/([0-9]*)/(.*)$ {
        types {
            text/html;
        }
        root           /home/admin/web/site.ru/public_html/cache;
        try_files      $1 @goapach;
    }
    ...
    location / {
        ...
    }
    ...
    location @goapach {
        proxy_pass      http://111.111.111.11:8080;
    }
}

test - respectively while for the test and without cookies. Sending to Apache...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
AlexeyPortnov, 2015-10-29
@AlexeyPortnov

Using If is bad practice, try to avoid and use map.
See "If is evil": https://www.nginx.com/resources/wiki/start/topics/...
nginx configuration errors (or how to write rewrites): habrahabr.ru/post/74135
map $http_cookie $ redirect1 {
default 0;
"~*qa_session" 1;
}
map $request_method $redirect2 {
default 0;
POST 1;
}
location ~^/([0-9]*)/(.*)$ {
set $cache_file $1;
set $redirect 0;
if ( "$redirect1$redirect2" ) {
return 412;
error_page 412 = @goapach;
}
types {}
default_type text/html;
try_files /qa-plugin/cache-master/cache/$cache_file @goapach;
}

A
Andrey, 2014-10-31
@amaslenn

Give it a try:
/it might be treated as a special character in a regular expression notation, depending on the engine you're using.
If the string needs to be searched for before the numbers, then you can try the following:
location ~/.*test\/\d+.*

V
Valery Correspondence, 2014-12-10
@Zilker

In general, I did this:

location ~^/([0-9]*)/(.*)$ {
    set $cache_file $1;
    set $redirect 0;
    if ( $http_cookie ~* qa_session ) {
        set $redirect 1;
    }
    if ( $request_method = POST ) {
        set $redirect 1;
    }
    if ( $redirect = 1 ) {
        return 412;
        error_page 412 = @goapach;
    }
    types {}
    default_type text/html;
    try_files /qa-plugin/cache-master/cache/$cache_file @goapach;
}

Authorized, POST requests and in the absence of a cache file we send to Apache (already php-fpm, not the point), otherwise we give the file from the cache.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question