【问题标题】:Is it possible to serve both "proxied content" and local files from the same domain using Nginx?是否可以使用 Nginx 为同一域中的“代理内容”和本地文件提供服务?
【发布时间】:2017-09-06 13:08:27
【问题描述】:

我有一个 Nginx 服务器配置为远程 Apache 服务器的反向代理缓存服务器。在这一点上,一切运行良好。这是我的配置的一部分(我留下了一些不相关的部分):

server {
        listen 443 ssl http2;
        server_name www.mywebsite.com mywebsite.com;

    location / {
        proxy_pass https://123.123.123.123;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header REMOTE_ADDR $remote_addr;
        proxy_ignore_headers X-Accel-Expires Expires Vary;
        proxy_redirect off;
        proxy_cache_revalidate off;
        proxy_next_upstream off;
        proxy_cache_use_stale error timeout invalid_header updating http_500 http_502 http_503 http_504;
        proxy_cache_bypass $bypass $do_not_cache;
        proxy_no_cache $do_not_cache;
        proxy_cache_valid any 2880m;
        proxy_cache_valid 404 1m;
        proxy_cache my_cache;
        proxy_cache_min_uses 1;
        proxy_cache_lock on;
        proxy_http_version 1.1;
    }   
}

现在我想做的是从存储在 Nginx 服务器上的本地文件中提供来自特定目录的文件。其余内容仍必须从源服务器缓存:

  • //www.mywebsite.com => 提供来自 //123.123.123.123 的缓存内容
  • //www.mywebsite.com/local => 提供本地存储在 Nginx 服务器上的文件

是否可以在配置的“服务器”部分中包含另一个位置?我尝试了类似的方法,但它不起作用:

location /local/ {
    root /home/user/public_html/local;
    try_files $uri $uri/ =404;
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Max-Age' 1728000;
}

顺便说一句,对不起我的英语。

【问题讨论】:

  • 如果您的问题已解决,请将答案标记为已接受

标签: nginx


【解决方案1】:

您的方法是正确的,您应该使用 alias 指令定义另一个 location

location /local/ {
    alias /home/user/public_html/local;
}

现在,当您请求http://YOUR_DOMAIN/local/page.html 时,它将提供/home/user/public_html/local/page.html

记住,nginx必须对指定的根目录有读权限。

阅读this for the subtle difference between root and alias 指令。

【讨论】:

  • 其实已经很接近了,但是“root”需要改成“alias”:
  • 谢谢@StephaneBrault,现在你可以接受了
猜你喜欢
  • 2018-11-28
  • 2011-09-17
  • 2021-01-22
  • 2013-04-15
  • 2016-12-15
  • 1970-01-01
  • 1970-01-01
  • 2014-07-25
  • 2014-07-01
相关资源
最近更新 更多