Search code examples
mod-rewritenginxcontent-management-systemstatic-pages

how to process dynamic urls as static pages using nginx?


I want my Nginx serve dynamical urls as static pages, e.g.

given a url  "/book?name=ruby_lang&published_at=2014" , 
the nginx will serve a static file (which is generated automatically ) named as:
"book?name=ruby_lang&published_at=2014.html"  or:
"book-name-eq-ruby_lang-pblished_at-eq-2014.html"

is this possible?

NOTE:

1.there's no static file named:

  "book?name=ruby_lang&published_at=2014.html" nor 
  "book-name-eq-ruby_lang-pblished_at-eq-2014.html"

however, I can generate them if needed.

2.I can't change the url that give to the consumer. e.g. my consumer could only send request to me via

  "/book?name=ruby_lang&published_at=2014"

but not with any other urls.


Solution

  • If you are OK with generating the HTML files yourself, you could simply use nginx's rewrite module. Example:

    rewrite ^/book book-name-eq-$arg_name-published_at-eq-$arg_published_at.html last;
    

    If you need to make sure that name and published_at are valid, you can instead do something like this:

    location = /book {
        if ($arg_name !~ "^[A-Za-z\d_-]+$") { return 404; }
        if ($arg_published_at !~ "^\d{4}$") { return 404; }
        rewrite ^/book book-name-eq-$arg_name-published_at-eq-$arg_published_at.html last;
    }
    

    This will make sure that published_at is a valid 4-digits integer, and name is a valid identifier (English alphabets, numbers, underscore, and hyphen).


    To make sure a book is only accessible from one URL, you should throw 404 if the URL is the HTML file. Add this before the previous rule:

    location ~ /book-(.*).html {
        return 404;
    }