How to serve all existing static files directly with NGINX, but proxy the rest to a backend server.

后端 未结 3 847
臣服心动
臣服心动 2020-11-28 00:47
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          


        
相关标签:
3条回答
  • 2020-11-28 01:40

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

    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.

    0 讨论(0)
  • 2020-11-28 01:42

    Try this:

    location / {
        root /path/to/root;
        expires 30d;
        access_log off;
    }
    
    location ~* ^.*\.php$ {
        if (!-f $request_filename) {
            return 404;
        }
        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;
    }
    

    Hopefully it works. Regular expressions have higher priority than plain strings, so all requests ending in .php should be forwared to Apache if only a corresponding .php file exists. Rest will be handled as static files. The actual algorithm of evaluating location is here.

    0 讨论(0)
  • 2020-11-28 01:44

    If you use mod_rewrite to hide the extension of your scripts, or if you just like pretty URLs that end in /, then you might want to approach this from the other direction. Tell nginx to let anything with a non-static extension to go through to apache. For example:

    location ~* ^.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$
    {
        root   /path/to/static-content;
    }
    
    location ~* ^!.+\.(jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|pdf|txt|tar|wav|bmp|rtf|js|flv|swf|html|htm)$ {
        if (!-f $request_filename) {
            return 404;
        }
        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;
    }
    

    I found the first part of this snippet over at: http://code.google.com/p/scalr/wiki/NginxStatic

    0 讨论(0)
提交回复
热议问题