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

后端 未结 3 871
臣服心动
臣服心动 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.

提交回复
热议问题