1

我希望我的 Nginx 将动态 url 作为静态页面提供,例如

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"

这可能吗?

笔记:

1.没有静态文件命名:

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

但是,如果需要,我可以生成它们。

2.我无法更改提供给消费者的网址。例如,我的消费者只能通过

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

但不是与任何其他网址。

4

2 回答 2

6

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;
}
于 2014-03-03T20:08:52.270 回答
1

好的,感谢@Alon Gubkin 的帮助,我终于解决了这个问题,(见:http : //siwei.me/blog/posts/nginx-try-files-and-rewrite-tips)。这里有一些提示:

  1. 使用“try_files”而不是“重写”

  2. 在静态文件名中使用“-”而不是下划线“_”,否则 nginx 在将 $arg_parameters 设置为文件名时会感到困惑。例如使用“platform-$arg_platform.json”而不是“platform_$arg_platform.json”

  3. 看看nginx 内置变量

这是我的 nginx 配置片段:

server {
  listen       100;
  charset utf-8;
  root /workspace/test_static_files;
  index index.html index.htm;

  # nginx will first search '/platform-$arg_platform...' file, 
  # if not found return /defautl.json 
  location /popup_pages {
    try_files /platform-$arg_platform-product-$arg_product.json /default.json;
  } 
}

我还将我的代码放在 github 上,以便对此问题感兴趣的人可以查看: https ://github.com/sg552/server_dynamic_urls_as_static_files

于 2014-03-15T10:55:59.640 回答