Home > other >  Nginx rewrite url with hash or md5
Nginx rewrite url with hash or md5

Time:11-12

My cms creates html files for caching based on their url. To prevent too many files in one directory, in inserts a slash after the thrid character.

So for example:

  • the url /some-text-article-4711 is md5 hashed to 88c7966ed723feb1cb4a83b48f723c56 and the cms stores the html file under 88c/7966ed723feb1cb4a83b48f723c56
  • the url /some-text/post-123 is md5 hashed to 8abfab6e4ab585984cc7fe53e129ee4d and the cms stores the html file under 8ab/fab6e4ab585984cc7fe53e129ee4d

Right now, the cms handles requests on (for example) /some-text-article-4711 and outputs the content of 88c/7966ed723feb1cb4a83b48f723c56. But it would be more efficent, if nginx could handle this without PHP.

Is there a way in nginx, to rewrite these requests to the correct form so it could serve these "static" files?

I can also change md5 to another hashing logic. The only reason for md5 is the "too many files in directory" probleme, since there are 100k urls under "/".

CodePudding user response:

Yes this is a great use case for njs.

https://nginx.org/en/docs/njs/

In your case I would create a variable using js_set or js_var.

Create a njs function that will calculate the md5 hash based on the uri and add the slash between the third and the fourth positions. You can then use a rewrite rule to rewrite the uri OR use try_files to get file from disk.

For a set of njs examples see https://github.com/xeioex/njs-examples/tree/master/njs/http

  • Related