如何直接使用 NGINX 服务所有现有的静态文件,但将其余的代理到后端服务器.

问题描述:

location / {
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

    if (-f $request_filename) {
        access_log off;
        expires 30d;
        break;
        }

    if (!-f $request_filename) {
        proxy_pass http://127.0.0.1:8080; # backend server listening
        break;
        }
    }

以上将直接使用 Nginx 提供所有现有文件(例如 Nginx 只显示 PHP 源代码),否则将请求转发给 Apache.我需要从规则中排除 *.php 文件,以便 *.php 的请求也传递给 Apache 并进行处理.

Above will serve all existing files directly using Nginx (e.g. Nginx just displays PHP source code), otherwise forward a request to Apache. I need to exclude *.php files from the rule so that requests for *.php are also passed to Apache and processed.

我想让 Nginx 处理所有静态文件,让 Apache 处理所有动态文件.

I want Nginx to handle all static files and Apache to process all dynamic stuff.

有白名单方法,但不是很优雅,查看所有这些扩展,我不想要这个.

There is white list approach, but it is not very elegant, See all those extensions, I don't want this.

location ~* ^.+.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js)$ {
    access_log off;
    expires 30d;
    }
location / {
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
    }

编辑 2:在较新版本的 Nginx 上使用 try_files 而不是 http://wiki.nginx.org/HttpCoreModule#try_files

EDIT 2: On newer versions of Nginx use try_files instead http://wiki.nginx.org/HttpCoreModule#try_files

使用 try_files 和命名位置块('@apachesite').这将删除不必要的正则表达式匹配和 if 块.效率更高.

Use try_files and named location block ('@apachesite'). This will remove unnecessary regex match and if block. More efficient.

location / {
    root /path/to/root/of/static/files;
    try_files $uri $uri/ @apachesite;

    expires max;
    access_log off;
}

location @apachesite {
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8080;
}

更新:这个配置的假设是/path/to/root/of/static/files下不存在任何php脚本.这在大多数现代 php 框架中都很常见.如果您的旧 php 项目在同一文件夹中同时包含 php 脚本和静态文件,您可能需要将您希望 nginx 服务的所有文件类型列入白名单.

Update: The assumption of this config is that there doesn't exist any php script under /path/to/root/of/static/files. This is common in most modern php frameworks. In case your legacy php projects have both php scripts and static files mixed in the same folder, you may have to whitelist all of the file types you want nginx to serve.