S
S
SFY2021-06-25 16:18:21
Nginx
SFY, 2021-06-25 16:18:21

How to do location/rewrite correctly?

server {
  listen 80;
  listen [::]:80;

  server_name site.ru;

  root /var/www/site.ru;
  index index.html;
  location ~* \.(?:jpg|jpeg|gif|png|webp)$ {
        expires 30d;
    }
    location ~* \.(css|js|woff2)$ {
    	expires 30d;
    }
    location / {
    try_files $uri $uri/ =404;
  }
    rewrite ^/([a-z,0-9,-]+)$ /pages/$1.html last;
  gzip                on;
    gzip_min_length     1000;
    gzip_proxied        expired no-cache no-store private auth;
    gzip_types          text/plain text/css text/javascript application/javascript application/x-javascript text/xml application/xml application/xml+rss application/json;
    gzip_disable        "msie6";
}


There is such a config.
The /var/www/site.ru folder contains pictures, fonts, scripts.
There is also a folder /var/www/site.ru/pages where already generated pages are located.
Pages look like: path.html

How it works now.
When a user navigates to site.ru/ page111 , the file /var/www/site.ru/pages/ page111 .html is given to him.

But there is a problem, namely, part of the page is generated page by page.
Example: site.ru/ bigpage?p={PAGE_NUMBER}
How to fix the config so that the file /var/www/site.ru/pages/ bigpage-{PAGE_NUMBER}.html
is returned And when the parameter ?={PAGE_NUMBER} is not specified, it will be returned simply / var/www/site.ru/pages/bigpage-1.html

It would be possible to register all this with pens, but pages are constantly being created and the task needs to be automatically solved.
Please advise me to solve this problem.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dodo512, 2021-06-25
@SFY

If there are no special differences in the names of ordinary and those that are divided into several pages.
Then it remains to sequentially check the existence of files.

location / {
    try_files $uri $uri/ =404;
}
rewrite ^/([a-z,0-9,-]+)$ /pages/$1.html last;

Change this snippet to:
location / {
    try_files $uri $uri/ /pages$uri-$arg_p.html /pages$uri-1.html /pages$uri.html =404;
}

You can close addresses like site.ru/pages/page.html and with non-existent page numbers site.ru/bigpage?p=999
rewrite ^/([a-z0-9-]+)$ /pages/$1-$arg_p.html last;

location ~ ^(/pages/.+)-\.html$ {
    internal;
    try_files $1-1.html $1.html =404;
}

location ~ ^/pages/.+\.html$ {
    internal;
    try_files $uri =404;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question