regexnginxnginx-confignginx-location

use regex for detect multi string in nginx location and rewrite


I want when a request is sent to the server and there is one of the string values of (movie|series|video|...) at the beginning, that string is removed and directed to the path where the data is stored.

this my nginx location config

 location ~ ^/(movie|series|video|...)/.*\.ts {
        add_header Access-Control-Allow-Origin *;
        add_header X-App-Id media-service-nginx;
        rewrite ^/(movie|series|video|...)/(.*)$ /$1 break;
        root /storage/media;
    }

And requests like these are sent to the server

http://api.media.loc/movie/2023/02/21/video-1080-chunk_intro_300.ts
http://api.media.loc/series/2023/02/21/video-1080-chunk_intro_200.ts
http://api.media.loc/video/2023/02/21/video-1080-chunk_intro_100.ts

Finally, the request should be redirected to the path, for example /storage/media/2023/02/21/video-1080-chunk_intro_300.ts

this config gives a 404 error for the multi string

But if a string is written in the config, it works correctly, ~ ^/movie/.*\.ts

I want it to support multi rules ~ ^/(movie|series|video|...)/.*\.ts and rewrite ^/(movie|series|video|...)/(.*)$ /$1 , this is not work , please help


Solution

  • I can see a minor mistake in your regex which you used in your rewrite rule. You need to use $2. The variable $1 represents the first capture group, which is the movie, series, or video part, while $2 represents the second capture group, which is the rest of the path. You can read this post for getting insights around capturing groups.

    Here's how it'll look like:

    location ~ ^/(movie|series|video)/.*\.ts {
        add_header Access-Control-Allow-Origin *;
        add_header X-App-Id media-service-nginx;
        rewrite ^/(movie|series|video)/(.*)$ /$2 break;
        root /storage/media;
    }