折腾了一晚上,终于搞定了。搜索了很久都没有搜到有相关的中文文章,甚至英文的都很少,全是generic的nginx部署防盗链的文章,特此总结整理一下方便以后查询。

想必nginx防盗链的部署方法大家都知道了,在装了Ghost的情况下稍稍有所不同,主要因为实际访问的文件不在根目录下,而是在ghost的安装目录中,所以要用到proxy。就因为这一点折腾了好久,症状就是加入防盗链代码后所有图片自动404,加了proxy之后就好了。

以下是我使用的代码:

location /content/ {
  valid_referers none blocked ~.google. ~.bing. ~.baidu. server_names ~($host);
  if ($invalid_referer) {
    rewrite ^/ http://ww1.sinaimg.cn/large/76b129b3gy1fisvu3x79lj21hc0u0ta2.jpg;
     }
   try_files $uri @ghost;
}


location @ghost {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://127.0.0.1:2368;
}

代码解释如下:

location /content/

↑因为ghost的特殊性,所有上传的图片都在content目录下,如有需求还是改成扫描文件后缀。

valid_referers none blocked ~.google. ~.bing. ~.baidu. server_names ~($host);

↑关于valid_referers网上的解释很多了,推荐阅读官网的定义。包含了几个搜索引擎,当然不希望图片被搜索引擎爬的也可以去掉,后面使用了host变量方便大家直接复制黏贴。

if ($invalid_referer) 

↑当来源没有列在上述列表中,$invalid_refererfan返回值为1,执行rewrite。

rewrite ^/ http://ww1.sinaimg.cn/large/76b129b3gy1fisvu3x79lj21hc0u0ta2.jpg;

↑rewrite到一个外部图床的防盗链图片,注意用自己的图片网址替换我的网址,如果不需要,可直接 return 444。

try_files $uri @ghost;

↑最重要的一步,因为实际访问的文件并不在服务器的root directory下,本身ghost-cli自动部署的nginx配置就带proxy。try_files的定义请看官方文档

location @ghost {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://127.0.0.1:2368;
}

↑这里我照抄了ghost-cli部署时写入的proxy代码。

写入conf之后重启nginx即可。

注:由于本站强制https访问,所以在http段直接设置了所有访问content都rewrite到盗链图片上:

location /content/ {
    rewrite ^/ http://ww1.sinaimg.cn/large/76b129b3gy1fisvu3x79lj21hc0u0ta2.jpg;
}