1

我希望我的Nginx服务动态网址为静态网页,例如如何使用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.there的命名没有静态文件:

"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" 

但没有与其他任何网址。

+0

你是什么意思的“serve as static”?你有名为“book-name-eq-ruby_lang-pblished_at-eq-2014.html”的文件? –

+0

你的CMS是否支持自定义网址? –

+0

我添加了评论,查看更新。谢谢 –

回答

6

如果您自己可以生成HTML文件,那么您可以简单地使用nginx的重写模块。例如:

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

如果您需要确保namepublished_at是有效的,可以改为做这样的事情:

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; 
} 

这将确保published_at是一个有效的4位数的整数,name是一个有效的标识符(英文字母,数字,下划线和连字符)。


要确保一本书只能从一个URL访问,如果该URL是HTML文件,则应该抛出404。之前添加此以前的规则:

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

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

  1. 使用'try_files'而不是'重写'

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

  3. 看看nginx built-in variables

,这是我的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

+0

你的博文是中文.... :( –

+0

哥们,所有的中文都是跟着英文翻译的。祝你好运! –

相关问题