nginx - serve only images

2019-02-02 00:05发布

问题:

I'm trying to setup nginx so "static.domain.com" can only serve images. This is what I have come up with, but I know it can be done more efficiently. I want to serve 403.html if someone tries to access any .htm, .php, directory (anything else I'm missing?) files. Of course, with the exception of 403.htm and static.htm files.

Any ideas how I can secure this properly?

server {
     listen          xx.xx.xx.xx:80;

     server_name     static.domain.com;

     root            /www/domain.com/httpdocs;
     index           static.htm;

     access_log      off;
     error_log       /dev/null crit;

     error_page  403  /403.html;

     # Disable access to .htaccess or any other hidden file
     location ~ /\.ht  {
        deny all;
     }

     location ~* \.php {
        deny all;
     }

     # Serve static files directly from nginx
     location ~* \.(jpg|jpeg|gif|png|bmp|ico|pdf|flv|swf|exe|html|htm|txt|css|js) {
        add_header        Cache-Control public;
        add_header        Cache-Control must-revalidate;
        expires           7d;
     }
}

回答1:

Why not move the images up and then deny all?

location ~* \.(jpg|jpeg|gif|png|bmp|ico|pdf|flv|swf|exe|html|htm|txt|css|js) {
   add_header        Cache-Control public;
   add_header        Cache-Control must-revalidate;
   expires           7d;
}
location  / {
    deny all; 
}

there is no syntax for NOT matching a regular expression. Instead, match the target regular expression and assign an empty block, then use location / to match anything else. -From http://wiki.nginx.org/HttpCoreModule#location

Edit: Removed "=" from "location /" To quote the docs:

location  = / {
  # matches the query / *only.* 
}
location  / {
  # matches *any query*, since all queries begin with /, but regular
  # expressions and any longer conventional blocks will be
  # matched first.
}

My bad.



标签: nginx