Nginx

Nginx 索引不在項目根目錄

  • May 21, 2019

我有一個 index.html 頁面,它與我的其他客戶端資源 ( /opt/django/media/index.html) 一起儲存。我可以讓 nginx 將頁面作為對域名的請求的索引,但是它就像它位於項目根目錄中而不是在媒體目錄中一樣提供它。這意味著images/123.png現在可以在頁面中訪問的圖像之類的內容必須media/images/123.png在我的 index.html 中進行。我應該只更新頁面中的資源路徑還是有更好的方法?我的配置如下:

server {
   listen   80;
   server_name localhost;

   access_log /opt/django/logs/nginx/vc_access.log;
   error_log  /opt/django/logs/nginx/vc_error.log;

   # no security problem here, since / is alway passed to upstream
   root /opt/django/;
   location = / {
       index media/index.html;
   }
   # serve directly - analogous for static/staticfiles
   location /media/ {
       # if asset versioning is used
       if ($query_string) {
           expires max;
       }
   }
   location /static/ {
       # if asset versioning is used
       if ($query_string) {
           expires max;
       }
   }
   location /metro/ {
       proxy_pass_header Server;
       proxy_set_header Host $http_host;
       proxy_redirect off;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Scheme $scheme;
       proxy_connect_timeout 10;
       proxy_read_timeout 10;
       proxy_pass http://localhost:8080/;
   }
   location / {
       proxy_pass_header Server;
       proxy_set_header Host $http_host;
       proxy_redirect off;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Scheme $scheme;
       proxy_connect_timeout 10;
       proxy_read_timeout 10;
       proxy_pass http://localhost:8000/;
   }
   # what to serve if upstream is not available or crashes
   error_page 500 502 503 504 /media/50x.html;
}

這是try_files的工作。

這樣的事情應該讓你開始:

server {
   # ...

   root /opt/django;

   location @django {
       proxy_pass_header Server;
       proxy_set_header Host $http_host;
       proxy_redirect off;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header X-Scheme $scheme;
       proxy_connect_timeout 10;
       proxy_read_timeout 10;
       proxy_pass http://localhost:8000/;
   }
   # what to serve if upstream is not available or crashes
   error_page 500 502 503 504 /media/50x.html;

   location / {
       try_files /media$uri $uri $uri/ @django;
   }
}

引用自:https://serverfault.com/questions/409945