Nginx虽然主要作为高性能的静态内容服务器和反向代理,但也可以通过多种方式实现动态内容生成。以下是几种常见方法:
SSI允许在HTML文件中嵌入动态内容指令:
server {
listen 80;
server_name example.com;
# 启用SSI处理
ssi on;
location / {
root /var/www/html;
index index.shtml;
}
}
在HTML文件中(如index.shtml):
<!--#echo var="DATE_LOCAL" -->
<!--#include virtual="/footer.html" -->
通过Perl模块嵌入动态逻辑:
http {
perl_modules perl/lib;
perl_require hello.pm;
server {
location /hello {
perl hello::handler;
}
}
}
创建perl/lib/hello.pm:
package hello;
use nginx;
sub handler {
my $r = shift;
$r->send_http_header("text/html");
return OK if $r->header_only;
$r->print("Hello, world! Current time: ", scalar localtime);
return OK;
}
1;
Nginx Plus和开源版本(1.9.11+)支持JavaScript动态处理:
load_module modules/ngx_http_js_module.so;
http {
js_include http.js;
server {
location /dynamic {
js_content dynamicResponse;
}
}
}
http.js内容:
function dynamicResponse(r) {
r.headersOut['Content-Type'] = 'text/plain';
r.return(200, "Dynamic response at " + new Date());
}
通过OpenResty或ngx_lua模块实现复杂动态逻辑:
location /lua {
default_type 'text/plain';
content_by_lua_block {
ngx.say("Hello from Lua!")
ngx.say("Request URI: ", ngx.var.request_uri)
ngx.say("Current time: ", os.date("%Y-%m-%d %H:%M:%S"))
}
}
最常见的动态内容生成方式:
location /api {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
选择哪种方法取决于您的具体需求、性能要求和开发团队的技术栈熟悉程度。