参考资料

  1. Nginxreferer:请求头控制模块详细说明以及案例
  2. Nginx配置文件中通过location块匹配静态资源类型,并添加缓存响应头
  3. 如何启用Nginx上游连接复用?
  4. Nginx如何用于反向代理?
  5. Nginx配置详细说明以及案例
  6. Nginx的常见错误及解决方案
  7. Nginx Logrotate:日志归档配置详细说明以及案例
  8. Nginxalias 访问路径别名指令详细说明以及案例

Nginx如何支持动态内容?

Nginx支持动态内容主要通过反向代理和FastCGI两种方式实现:

  1. 反向代理方式(以Node.js为例):

server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://localhost:3000; # 后端应用服务器地址
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}
  1. FastCGI方式(以PHP为例):

server {
    listen 80;
    server_name example.com;

    root /var/www/html;
    index index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}
  1. 其他动态语言支持:

  • Python (uWSGI):

location / {
    include uwsgi_params;
    uwsgi_pass unix:/tmp/uwsgi.sock;
}
  • Ruby (Passenger):

passenger_enabled on;
passenger_ruby /usr/bin/ruby;

关键配置说明:

  1. proxy_pass:将请求转发到后端应用服务器

  2. fastcgi_pass:通过FastCGI协议与PHP处理器通信

  3. uwsgi_pass:与Python应用服务器通信

  4. 需要确保Nginx能访问到后端服务(通过socket或TCP端口)