Ubuntu
為特定 url 啟用 nginx 瀏覽器記憶體
如何為特定 URL 啟用 nginx 記憶體?我有一個 django web 應用程序,我將我的靜態文件(如 CSS、JavaScript 和 …)放在一個名為 static 的文件夾中,我可以通過http://example.com/static/訪問它們,我想配置 nginx n僅從此 url 擷取這些文件。我已經閱讀了http://www.nginxtips.com/how-to-enable-browser-cache-static-files-on-nginx/但是這裡沒有解釋這個選項。我嘗試了以下配置並重新啟動了我的 nginx 伺服器,但出現了錯誤。這是我的
sites-available/default
配置文件。有什麼問題?server { listen 80; listen 443 ssl; server_name www.example.com example.com; ssl_certificate /var/www/example/ssl/ssl.crt; ssl_certificate_key /var/www/example/ssl/ssl.key; location /static (jpg|jpeg|png|gif|ico|css|js)$ { alias /var/www/example/static; expires 3d; add_header Pragma public; add_header Cache-Control "public, must-revalidate, proxy-revalidate"; } location /media { alias /var/www/example/media; } location / { proxy_pass http://127.0.0.1:8000; } }
這是 nginx 日誌文件內容…
2014/03/07 13:02:28 [error] 25189#0: *22 open() "/etc/nginx/html/static/css/wait.css" failed (2: No such file or directory), client: 2.178.27.157, server: www.example.com, request: "GET /static/css/wait.css HTTP/1.1", host: "example.com", referrer: "http://example.com/" 2014/03/07 13:02:28 [error] 25189#0: *23 open() "/etc/nginx/html/static/img/infographi.png" failed (2: No such file or directory), client: 2.178.27.157, server: www.example.com, request: "GET /static/img/infographi.png HTTP/1.1", host: "example.com", referrer: "http://example.com/" 2014/03/07 13:02:29 [error] 25189#0: *23 open() "/etc/nginx/html/favicon.ico" failed (2: No such file or directory), client: 2.178.27.157, server: www.example.com, request: "GET /favicon.ico HTTP/1.1", host: "example.com" 2014/03/07 13:08:41 [emerg] 25220#0: invalid location modifier "/static" in /etc/nginx/sites-enabled/default:8 2014/03/07 13:08:41 [emerg] 25221#0: invalid location modifier "/static" in /etc/nginx/sites-enabled/default:8 2014/03/07 13:09:50 [emerg] 25255#0: invalid location modifier "/static" in /etc/nginx/sites-enabled/default:8 2014/03/07 13:09:50 [emerg] 25256#0: invalid location modifier "/static" in /etc/nginx/sites-enabled/default:8
從nginx wiki看來,您在“/static”和您的正則表達式模式之間有一個空格。Location 只接受一個“uri”參數,而不是兩個……並且 nginx 會將該空間解釋為參數分隔符。
此外,您還需要告訴位置塊您想將正則表達式與“~”或“~*”修飾符匹配。
你可以試試這個
location ~* "/static.*(jpg|jpeg|png|gif|ico|css|js)$" {
而不是你所擁有的,看看它是否符合你的要求。
您在此文件夾中還有其他文件嗎?如果你沒有,或者如果可以讓它們暴露,你可以簡化配置:
server { listen 80; listen 443 ssl; server_name www.example.com example.com; ssl_certificate /var/www/example/ssl/ssl.crt; ssl_certificate_key /var/www/example/ssl/ssl.key; root /var/www/example; location / { proxy_pass http://127.0.0.1:8000; } location /media/ { # it's ok to have empty location } location /static/ { expires 3d; add_header Pragma public; add_header Cache-Control "public, must-revalidate, proxy-revalidate"; } }