【问题标题】:how to process dynamic urls as static pages using nginx?如何使用 nginx 将动态 url 处理为静态页面?
【发布时间】:2014-03-28 18:30:38
【问题描述】:

我希望我的 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"

但不包含任何其他网址。

【问题讨论】:

  • “充当静态”是什么意思?你有名为“book-name-eq-ruby_lang-pblished_at-eq-2014.html”的文件吗?
  • 您的 CMS 支持自定义 URL 吗?
  • 我添加了 cmets,查看更新。谢谢
  • 文件真的是静态的还是按需生成的?只是您需要支持的特定 URL 还是某些 URL 方案?

标签: mod-rewrite nginx content-management-system static-pages


【解决方案1】:

如果你可以自己生成 HTML 文件,你可以简单地使用 nginx 的 rewrite 模块。示例:

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

【讨论】:

    【解决方案2】:

    好的,感谢@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 built-in variables

    这是我的 nginx 配置 sn-p:

    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

    【讨论】:

    • 哥们,中文后面都是英文翻译。祝你好运!
    猜你喜欢
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    相关资源
    最近更新 更多